Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over arguments in a bash script and make use of their numbers

If I want to iterate over all arguments it is as easy as for i in "$@"; do .... However, let's say I want to start with the second argument and also make use of the arguments' positions for some basic calculation.

As an example I want to shorten these commands into one loop:

grep -v 'foobar' "$2" | grep -f $file > output1.txt
grep -v 'foobar' "$3" | grep -f $file > output2.txt
grep -v 'foobar' "$4" | grep -f $file > output3.txt
grep -v 'foobar' "$5" | grep -f $file > output4.txt

I tried many variations like for i in {2..5}; do grep -v 'foobar' "$$i" | grep -f $file > output$(($i-1)).txt; done; however, it seems bash expansion doesn't work like this.

EDIT:

Seems I made a mistake not emphasizing that I need to make use of the argument's position/number (i.e., 2 from $2). It's important because the output files get used separately later in the script. All of the provided answers so far seem correct but I don't know how to use them to make use of the argument's "number".

like image 971
user2044638 Avatar asked May 05 '16 14:05

user2044638


People also ask

How do I iterate over a range of numbers defined by variables in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.

How do you pass a number argument in shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

How can we get the number of arguments supplied to a script?

You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments".

How do you pass arguments in a bash script?

In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3 … The second argument will be referenced by the $2 variable, the third argument is referenced by $3 , .. etc. The $0 variable contains the name of your bash script in case you were wondering!


2 Answers

Couple correct answers already, another way could be:

for (( i=2; i <= "$#"; i++ )); do
    echo "arg position: ${i}"
    echo "arg value: ${!i}"
done
like image 169
Jstills Avatar answered Oct 19 '22 18:10

Jstills


If you do not want to shift off the first unneeded arguments you can use the indirection expansion:

for i in {2..5}; do
  echo "${!i}"
done
like image 36
Andreas Louv Avatar answered Oct 19 '22 17:10

Andreas Louv