Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through parameters skipping the first

Tags:

bash

Hi i have the following:

bash_script parm1 a b c d ..n

I want to iterate and print all the values in the command line starting from a, not from parm1

like image 226
piet Avatar asked Aug 26 '10 13:08

piet


3 Answers

You can "slice" arrays in bash; instead of using shift, you might use

for i in "${@:2}"
do
    echo "$i"
done

$@ is an array of all the command line arguments, ${@:2} is the same array less the first element. The double-quotes ensure correct whitespace handling.

like image 112
Ismail Badawi Avatar answered Sep 20 '22 02:09

Ismail Badawi


This should do it:

#ignore first parm1
shift

# iterate
while test ${#} -gt 0
do
  echo $1
  shift
done
like image 29
Scharron Avatar answered Sep 22 '22 02:09

Scharron


This method will keep the first param, in case you want to use it later

#!/bin/bash

for ((i=2;i<=$#;i++))
do
  echo ${!i}
done

or

for i in ${*:2} #or use $@
do
  echo $i
done
like image 9
ghostdog74 Avatar answered Sep 22 '22 02:09

ghostdog74