Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell $@ variable assignment and iteration

Tags:

bash

shell

sh

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

f 'hello world' 'second arg' '3rdarg'

this works fine:

hello world
second arg
3rdarg

but when do I assign $@ to some variable, and then it goes wrong:

function f() {
    local args="$@"
    for arg in "$args"; do
        echo "$arg"
    done
}

output:

hello world second arg 3rdarg

when I unquote the $args, then each argument was split into single word:

hello
world
second
arg
3rdarg

Lastly, I wonder if there's a way to define variable like $@. Any response will be appreciated.

like image 266
oxnz Avatar asked Nov 10 '15 04:11

oxnz


People also ask

What does $@ mean in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

How do I assign a value to another variable in shell script?

We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.

How do you assign a value to a variable in bash?

The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

What is #$ in shell script?

#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments).


Video Answer


1 Answers

You'll need to use an array:

function f() {
    local args=("$@")             # values in parentheses
    for arg in "${args[@]}"; do   # array expansion syntax
        echo "$arg"
    done
}
like image 88
glenn jackman Avatar answered Oct 02 '22 14:10

glenn jackman