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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With