Simple Bash function to use md5sum for string input

md5 hashing is known to be crackable. For non-sensitive usages, however, it's an easy and reliable algorithm. Here's how to easily hash strings with md5.

Using macOS for most of my work, if I want to retrieve the hash of a string, macOS provides an easy md5 function, located under /sbin/md5 and callable in any terminal:

$ md5 -s 'Hey md5!'

Linux does things a little differently, but with a single line in Bash, you can keep the easy macOS syntax.

Problem

I was pretty surprised that Debian 12 doesn’t have the same binary for md5 hashing as macOS. What it has is md5sum, which is part of the coreutils library. However, this reads files, not strings, that I attach as parameters. Hashing a string is possible with md5sum, but I found it a little too annoying to type it out every time, especially when I’m used to macOS’ way:

$ echo -n 'Hey md5!' | md5sum | awk '{print $1}'

Using it as an alias doesn’t work since the actual string is in the very front of the command, and, as far as I know, there are no placeholders.

Solution

The solution was to put it into a function inside my ~/.aliases file (which is read from ~/.bashrc, or /root/.bashrc):

md5() { echo -n $1 | md5sum | awk '{print $1}'; }

Now, I can simply run the following command, similar to macOS:

$ md5 'Hey md5!'

# Outputs: 36411828b72a71018c5a30fdffb68a7b

I personally prefer to move functions into /usr/local/bin so that it can be executed system-wide:

$ touch md5
$ nano md5 # ENTER: echo -n $1 | md5sum | awk '{print $1}';
$ mv md5 /usr/local/bin

That’s it. Now, the function works as a system-wide binary and generates the same hash as the function in .bashrc:

$ md5 'Hey md5!' # OUTPUT: 36411828b72a71018c5a30fdffb68a7b

That’s all. A small customization for lazy programmers like me that comes in quite handy.