iterate through shell script arguments

How to Iterate Over Arguments in Shell Script

Shell Scripts allow you to pass input parameters to customize the result and processing as per user requirements. While parsing input parameters, you may need to loop through arguments in shell script. In this article, we will learn how to iterate over arguments in shell script.


How to Iterate Over Arguments in Shell Script

Basically, there are a few predefined shell variables that hold all input parameters. They are “$@”, “$*”, $@ and $*.

Among them, “$@” is the most comprehensive variable that can be used to represent all input variables. I It is an array of input arguments that can be looped over and its individual elements can be accessed using indexes. Here is an example.

for var in "$@"
do
    echo "$var"
done

In the above “$@” variable, all arguments are stored separately in an array. When you input shell script arguments, they will be separated by spaces, and split into individual array elements. But quoted arguments are treated as a single value even if they contain spaces in them. Let us say you have the above code in your shell script test.sh and you call it as shown below.

$ sh test.sh 1 2 '3 4'
1
2
3 4

As you can see, ‘3 4’ is considered as a single argument.

Now let us look at how the other shell variables work. Both $@ and $* work in the same way. They treat each sequence of non-whitespace characters as a separate argument.”$*” treats the arguments as a single space-separated string. But $@ treats each space separated sequence of characters as a separate argument, unless they are quoted. In case they are quoted, the entire string within quotes is treated as a single argument.

When no arguments are specified “$@” evaluates to null value but “$*” evaluates to empty string.

One of the most common requirements for shell script developers is to be able to loop through arguments excluding the first argument.

You can easily do this by slicing the array. “$@” contains the array of input arguments. To exclude first argument, use the expression “${@:2}”. Here is an example.

for i in "${@:2}"
do
    echo "$i"
done

Now if you call your shell script as before, you will see a different output.

$ sh test.sh 1 2 '3 4'
2
3 4

In this article, we have learnt several ways to parse command line arguments.

Also read:

Bash Script That Takes Optional Arguments
How to Test If Variable is Number in Shell Script
How to Check if Variable is Number in Python
How to Take Backup of MySQL database in Python
How to Prevent Accidental File Deletion

Leave a Reply

Your email address will not be published. Required fields are marked *