Bash custom shell command

Super short post on creating your own custom shell command using Bash. You could do something very advanced using a general purpose or system level programming language such as Go, but most of the time a simple shell script will suffice.

The downside of using a shell script is that you have to to either source it source ~/ or execute it direcly bash ~/ The best way to work around this is to do the following:

Here is our script:

#! /bin/bash

echo "hello $1"

As you can see the file specifies the bash binary as the executable to use when the user executes this script, followed by the special variable $1 which refers to the first argument provided by the user (e.g. <your_command> arg1 arg2 arg3).

Note: you can use the bash default-value syntax ${1:-foo} where this equates to: if a $1 value hasn't been provided, then use the value foo

We'll save this file as testz (no file extension) into the folder /usr/local/bin, which is accessible from our $PATH. We can see this by running echo $PATH.

Because we save the file into a location accessible to $PATH it means we can just reference the name of the file and it'll be found and executed (hence we specify in the file what type of binary should be used to execute the file).

The only other thing we need to do is to ensure our users can execute the file. To do this, run the following:

chmod +x /usr/local/bin/testz

Now we can use this new custom command like so:

testz mark

Doing this will result in the following stdout result hello mark

So in future if you want to do some simple scripting and have it abstracted into a custom command, then these tips should help.