How do I output each argument to a Bash function?

I want to output all the arguments of a function one by one.
The function can take many arguments, $ # is the length of the arguments.

showArg(){
    num=$#
    for order in `seq 1 ${num}`
    do
        echo $order
    done
}

      

To fulfill it.

showArg  x1 x2 x3 
1
2
3

      

How do I fix the echo statement echo $order

to get this output:

x1
x2
x3

      

I've tried it echo $$order

.

To call any argument with a "$ @" loop in the loop, it can enumerate it, but that is not what I expected.

showArg(){
    for var in "$@"
    do
        echo "$var"
    done
}

      

+3


source to share


3 answers


You can use indirect actions:

showArg() {
  num=$#
  for order in $(seq 1 ${num}); do # `$(...)` is better than backticks
    echo "${!order}"               # indirection
  done
}

      

Using a C-style loop (as suggested by @chepner and @CharlesDuffy) the above code can be rewritten as:

showArg() {
  for ((argnum = 1; argnum <= $#; argnum++)); do
    echo "${!argnum}"
  done
}

      

But Bash provides a much more convenient way to do this - use "$@"

:



showArgs() {
  for arg in "$@"; do  # can also be written as: for arg; do
    echo "$arg"        # or, better: printf '%s\n' "$arg"
  done
}

      


See also:

+3


source


You don't need an explicit loop:



printf '%s\n' "$@"

      

+2


source


It is generally easier to use "$ *" to represent all arguments, so:

#!/bin/bash

for arg in $*
do
    echo $arg
done

      

In fact, this is the default behavior for a 'for' loop, so it in

can be stopped:

#!/bin/bash

for arg
do
    echo $arg
done

      

If you really want to use ordinal numbers, you can use the exclamation mark syntax, which uses the supplied variable's value as the name, so:

#!/bin/bash

num=$#
for order in $(seq 1 ${num})
do
    echo ${!order}
done

      

-4


source







All Articles