tags:

views:

92

answers:

3

I'm writing a bash script that needs to loop over the arguments passed into the script. However, the first argument shouldn't be looped over, and instead needs to be checked before the loop.

If I didn't have to remove that first element I could just do:

for item in "$@" ; do
  #process item
done

I could modify the loop to check if it's in its first iteration and change the behavior, but that seems way too hackish. There's got to be a simple way to extract the first argument out and then loop over the rest, but I wasn't able to find it.

+7  A: 

Use shift?

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html

Basically, read $1 for the first argument before the loop (or $0 if what you're wanting to check is the script name), then use shift, then loop over the remaining $@.

Amber
See, I *knew* there was a simple answer. :)
Herms
+1  A: 
fistitem=$1
shift;
for item in "$@" ; do
  #process item
done
nos
Remember that `$0` is generally the script name.
Amber
+1  A: 

Another variation uses array slicing:

for item in "${@:2}"
do
    process "$item"
done

This might be useful if, for some reason, you wanted to leave the arguments in place since shift is destructive.

Dennis Williamson