A guide to handling Bash script with positional arguments


3 min read

Bash scripts often require the ability to process both positional and named (or optional) arguments. Understanding how to handle these types of arguments can greatly enhance the flexibility and functionality of your scripts.

Bash provides several special parameters such as $@, $#, and $* that are crucial for handling command-line arguments effectively within scripts.

In this article, we will focus on positional arguments. Positional arguments are the most straightforward way to pass arguments to a script. They are accessed using special parameters like $1, $2, $3 and so on. You can also use $@ to refer to all positional parameters and $# to get the number of arguments.

Let us look at positional arguments in action using an example. Create a new file named run.sh as below:


echo "Script name: $0"
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Number of arguments: $#"
echo "All arguments: $@"

When you run ./run.sh arg1 arg2 arg3, the output is as below:

Script name: ./run.sh
Argument 1: arg1
Argument 2: arg2
Number of arguments: 3
All arguments: arg1 arg2 arg3

Ensure to make the script executable using chmod +x run.sh before running it.

I have often dealt with scenarios were some of positional arguments are used by the primary script and the rest of the arguments are passed to another script being called such as a Python script or another Bash script.

Let us look to an example of how to handle this. To start with let us assume that the primary script named run.sh takes 4 positional arguments, out of which the first 2 is used by this script and the next 2 are to passed to a called script named backup.sh. Assume that backup.sh has some functionality around backing up something like a database.

Create backup.sh script with the content as below:


echo "-----"
echo "Script name: $0"
echo "Argument 1: $1"
echo "Argument 2: $2"

# Rest of script functionality left out for brevity...

We are printing the name of script and the argument passed to it.

Now create run.sh as below:


echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"

# shift by 2 positional arguments from left
shift 2

# call backup.sh
./backup.sh $@

shift command is used to shift the positional parameters to the left. In our example, we have moved it by 2 positional arguments. When you use `$@`, this will have the rest of the positional arguments after the shift operation.

When you run ./run1.sh arg1 arg2 arg3 arg4 , the output is as below:

Script name: ./run1.sh
Number of arguments: 4
All arguments: arg1 arg2 arg3 arg4
Script name: ./backup.sh
Argument 1: arg3
Argument 2: arg4

Happy coding and scripting!