Using a range of command line arguments in bash for a loop prints brackets containing arguments

This is probably a lame question. But I get 3 arguments from the command line [bash script]. Then I try to use them in a for loop.

for i in {$1..$2} do action1 done 

This does not seem to work, and if $1 is "0" and $2 is 2 , it prints {0..2}' and calls action1` only once. I have referenced various examples, and this seems to be the correct use. Can someone please tell me what needs to be fixed here?

Thanks in advance.

+45
command-line bash loops for-loop arguments
Apr 17 '11 at 2:45
source share
5 answers

What about:

 for i in $(eval echo {$1..$2}); do echo $i; done 
+50
Apr 17 2018-11-11T00:
source share

You can slice the input using ${@:3} or ${@:3:8} and then iterate over it

For example, to print arguments starting at 3

 for i in ${@:3} ; do echo $i; done 

or type 8 arguments, starting with 3 (so, arguments 3 through 10)

 for i in ${@:3:8} ; do echo $i; done 
+64
Oct. 14 2018-11-11T00:
source share

Use the variable $ @?

 for i in $@ do echo $i done 

If you just want to use the 1st and 2nd arguments, just

 for i in $1 $2 

If your $ 1 and $ 2 are integers and you want to create a range, use the C syntax for the loop (bash)

 for ((i=$1;i<=$2;i++)) do ... done 
+14
Apr 17 2018-11-11T00:
source share

I had a similar problem. I think the problem is dereferencing $ 1 in brackets {} '. The following alternative worked for me.

 #!/bin/bash for ((i=$1;i<=$2;i++)) do ... done 

Hope this helps.

+6
Dec 22 '12 at 17:05
source share
 #/bin/bash for i do echo Value: $i done 

This will cover all the arguments given in the script file. Note that there is no โ€œdoingโ€ or anything else after the i loop variable.

0
04 Sept. '13 at 8:33
source share



All Articles