Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with function arguments and for loop in bash

Tags:

bash

Why doesn't this print all the passed arguments, in bash?

function abc() {
    echo "$1" #prints the correct argument

    for x in `seq 1 $#`; do
        echo "$x" #doesn't print the 1st, 2nd, etc arguments, but instead 1, 2, ..
    done
}

It is printing

1
2
3
4
...

instead.

like image 341
devoured elysium Avatar asked Dec 04 '22 11:12

devoured elysium


2 Answers

I'll just add a couple more options to what everyone else has given. The closest to the way you're trying to write this is to use bash indirect expansion:

function abc() {
    for x in `seq 1 $#`; do
        echo "${!x}"    # the ! adds a level of indirection
    done
}

...another option if you want to operate on only some of the arguments, is to use array slicing with $@:

function def() {
    for arg in "${@:2:3}"; do  # arguments 2 through 4 (i.e. 3 args starting at number 2)
        echo "$arg"
    done
}

similarly, "${@:2}" will give you all arguments starting at number 2, "${@:$start:$((end-start+1))}" will give you arguments $start through $end (the $(( expression calculates how many arguments there are between $start and $end), etc...

like image 112
Gordon Davisson Avatar answered Jan 15 '23 02:01

Gordon Davisson


Actually there is a special short-hand for this case:

function abc() {
  for arg ; do
    echo "$arg"
  done
}

That is, if the in ... part is omitted, arg loops over the function's argument $@.

Incidentally if you have for arg ; ... outside of a function, it will iterate over the arguments given on the command line.

like image 30
Chen Levy Avatar answered Jan 15 '23 02:01

Chen Levy