Bash Script Arguments

We’re now able to create a shell script, but this script will just do the same thing each time you run it. We can make it infinitely more interesting by using arguments.

Here’s an example, call it arguments.sh:

#!/bin/bash
echo "Hello $1, from $0"

If we run this with one argument, the result is as follows:

$ ./arguments.sh Weirdo
Hello Weirdo, from ./arguments.sh

What Bash does, is chop up your entire command and assign it to the not very imaginative variables $0, $1, $2, et cetera. As you can see, the first part of our command is the name of the script itself. This can come in handy, as can be seen in the next section.

A Much-Needed Safety Net

Before moving on to the serious stuff, I want to teach you about an important safety net.

Once you start creating scripts, you will inevitably make mistakes. We all do. One very common mistake in scripts can be especially disastrous. It’s the unset variable. If you don’t know what I mean, just keep reading as it will become clear in a moment.

We can prevent using unset variables by starting our scripts with the following command:

set -u

That’s all! From here on, your script is treating unset variables as an error when you are substituting.

For example, this script will fail:

#!/bin/bash
set -u
rm -rf /$my_directory

The output:

$ ./test.sh                                                          
./test.sh: 3: ./test.sh: my_directory: parameter not set

That’s because I never set $my_directory. Without set -u, it won’t fail but instead just ignore the empty variable, leaving us with the command rm -rf /. We all know what that does, right? If executed by a privileged user (like root), this mistake would have wiped my entire filesystem instead of the directory I intended to delete.

Make a habit of always starting your scripts with set -u


If you liked this page, please share it with a fellow learner: