Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using command line argument range in bash for loop prints brackets containing the arguments

It's probably a lame question. But I am getting 3 arguments from command line [ bash script ]. Then I am trying to use these in a for loop.

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

This doesn't seem to work though and if $1 is "0" and $2 is 2 it prints {0..2}' and callsaction1` only once. I referred to various examples and this appears to be the correct usage. Can someone please tell me what needs to be fixed here?

Thanks in advance.

like image 638
ru4mqart668op514 Avatar asked Apr 17 '11 02:04

ru4mqart668op514


People also ask

How does bash handle command line arguments?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.

What does $# in bash mean?

$# is the number of positional parameters passed to the script, shell, or shell function. This is because, while a shell function is running, the positional parameters are temporarily replaced with the arguments to the function. This lets functions accept and use their own positional parameters.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

Which loop does bash provide to iterate over a group of values and perform some commands on each one?

Use the for loop to iterate through a list of items to perform the instructed commands.


1 Answers

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

For eg., to print arguments starting from 3

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

or to print 8 arguments starting from 3 (so, arguments 3 through 10)

for i in ${@:3:8} ; do echo $i; done 
like image 115
Vijayender Avatar answered Sep 20 '22 00:09

Vijayender