Skip to main content
Bash Scripting

Making use of BASH Script Arguments

By July 26, 2016September 12th, 2022No Comments

Using BASH Script Arguments

BASH Script ArgumentsIn this blog we take a look at how we can use and make use of BASH script Arguments and what this all means to us. We will look at the variable that represents the script $0. As well as all the arguments from $1 through to $9. Where we need double values we can use ${10}. After all we all need at least 10 arguments to our scripts don’t we. Should we need to count the arguments we can us $# and $* represents all arguments. So lets slow down a little and look at what all this means.

The Script Name


All too often we do need to use the variable $0 which represents the full path to the script. I say all too often is that we use this is an error message all of the time. Perhaps in a usage statement when the input is not correct:

if test -z $username && echo "Usage: $0 <username>"

This would print something like: Usage: /usr/bin/listuser.sh <username> . In this way we can see that we must run the script and provide a username.

Script Arguments

We can provide arguments to the script. This are often call positional parameters as the numbers of the variable comes from their numerical position. $1 being the first argument, $2 being the second BASH script argument. Our numbering is straight forward until we need double figures when we need to use the brace brackets {}, to delimit the variable name. So the tenth argument would be ${10}. We can see that providing bash script arguments is not really that difficult:

echo "Argument 1 is $1"
echo "Argument 2 is $2"
echo "Hello $1 $2"

Argument Count

If we need to check the correct number of arguments have been provided before we continue we can make use another of the BASH script arguments. This time $#.

if [ ! $# -eq 1 ]
  then
    echo "You must provide exactly one argument to the script"
    echo "Usage $0 <username>
    exit 1
fi

In this example using BASH script arguments we check for the argument count value using $#. It has to be equal to 1, if it is no then we enter the if block and echo the usage statement before leaving the script.

All Arguments

If we need to cater for all the arguments then we have a variable $* the represents all the arguments as a list.

echo "Hello $*"

So if we run the script as: prompt.sh andrew mallett . The response will be Hello andrew mallett. Note that the script will not correct case. The variable $* is often used with BASH loops to we can iterate through each argument provided to the script.

The following video steps you through the process.


My Book on Shell Scripting is available from good book shops and the publisher Packt.
shellscripting