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
}
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.
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.
We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.
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.
#$ 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).
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
}
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