How to use Loops with $@ – Loop Constructs In Linux
Though positional parameters help to send as command-line arguments, if there are more arguments, we cannot count and use them. Instead by using $@, we can achieve that. It is nothing but the array of all the parameters passed. Iterating over a for loop, we can get that.
Output :
Another way is by using the Shift operator instead of $@ – Shift operator:
The $# variable is used to return the input size. By using that and with the shift operator we can achieve instead of $@
Output:
General Use case scenario using Shift operator:
Assume that in the command arguments, we may pass the “-d” argument which is nothing but to know it is a directory.
- If there is -d is given, then we need to pick the next argument and check is it a directory like that.
- If there is no -d, then check whether is it a file or not
Then display accordingly as to whether the argument is a directory or file
Let the name of the script be “shiftArgument.sh”
sh shiftArgument.sh -d /home shiftArgument.sh
Output:
The above code will check “/home” as a directory as we have “-d” as the first positional argument and hence shift operator is done and the next argument is checked against to see is it a directory. If there is no “-d” argument as the prior one, it just checks “whether that argument is a file or not”
Bash Script – How to use Command Line Arguments
In this article, let us see about Command Line Arguments usage in Bash script. Arguments are inputs that are necessary to process the flow. Instead of getting input from a shell program or assigning it to the program, the arguments are passed in the execution part.