Copy all script arguments to another variable

2019-05-27 11:44发布

问题:

I need to copy all script arguments and pass them to another script. I have tried to do it like this:

args=$@    
printargs.sh $args
echo ------
printargs.sh "$args"

but in such case if i call my parent script with arguments containing spaces e.g.:

script.sh "arg 1" "arg 2"

then it prints

arg
1
arg
2
----
arg 1 arg 2

How should I do this in bash or alternatively to be compatible with POSIX?

回答1:

$@ is like an array, so your temporary storage needs to be an array:

args=( "$@" )      # quotes are needed there

And then to use them:

printargs.sh "${args[@]}"