Question

If I have this on the command line:

bin/my_file --name "this name with whitespace" dir/some_file

Then in my script:

full_cmd="$@"
# later...
"$full_cmd"

The quotation marks are not preserved. This is the closest I've come:

 app=$1
 shift
 $app "$@"

However, it would be convenient if it were possible to save the "$@" into a variable to re-use later, like this:

 my_func () {
    $app "$args"
 }

I haven't been able to make any of that work... other than messy for loops. I'm new to bash. I've search all other possible solutions and can't figure out why this is so hard. Am I missing something obvious?

Was it helpful?

Solution 2

@choroba answer is good but you need to know that $0 is not in $@. As well here is an alternative:

printf -v myvar '%q ' "$@"

Then you have the strings shell escaped and thus will be correctly interpreted as separate arguments. And let me not forget - you need to use eval for invoking the command from the variables!

btw here $myvar is a normal string variable. It is not an array like in the above case. It is just that separate arguments are shell escaped with spaces in between.

Hope this helps.

Resources:

OTHER TIPS

$@ is an array. Store it in an array:

ar=("$@")
"${ar[@]}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top