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.

Program3 that contains $@

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 $@

Program4

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

In the comments, the flow is defined

Let the name of the script be “shiftArgument.sh”

sh  shiftArgument.sh -d /home shiftArgument.sh 

Output:

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.

Similar Reads

Positional Parameters

Command-line arguments are passed in the positional way i.e. in the same way how they are given in the program execution.  Let us see with an example....

Using Flags

Arguments can be passed along with the flags. The arguments can be identified with a single letter having – before that. A single letter can be meaningful and here let us take -1, -2, and -3....

Using Loops with $@ – Loop Constructs

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....

Conclusion

We can pass command-line arguments at our convenience in a positional way or with flags. Moreover useful concepts like $@ (array of all the parameters), $# (by calculating input size)  are available and with that, we can iterate in the  “for” or “while” loops, we can access the arguments....