Bash Script Arguments

We’re now able to create a shell script, but this script will 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

echo "Hello $1, from $0"

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

$ ./ Weirdo
Hello Weirdo, from ./

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:

set -u
rm -rf /$my_directory

The output:

$ ./                                                          
./ 3: ./ 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.

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!