1

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?

dgo.a
  • 2,634
  • 23
  • 35

2 Answers2

5

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

ar=("$@")
"${ar[@]}"
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Where did you learn this answer? I know it's basic, but was it in some `man` or some introductory publication? – dgo.a Aug 22 '13 at 16:58
  • 2
    Everything is in `man bash`, but I learned some details and tricks from Advanced Bash-Scripting Guide, too. – choroba Aug 22 '13 at 16:59
  • 1
    The [BashFAQ at Greg's wiki](http://mywiki.wooledge.org/BashFAQ) is another good reference. – Gordon Davisson Aug 22 '13 at 18:16
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:

akostadinov
  • 17,364
  • 6
  • 77
  • 85
  • It helped a lot. Thanks for pointing out the need for `eval`. I made a few changes for clarity. Hopefully, they don't violate best practices. – dgo.a Aug 23 '13 at 03:26
  • Nevermind about the edits. The editors say it's too much/too little. If anyone is interested: `printf`: http://wiki.bash-hackers.org/commands/builtin/printf `why eval is necessary`: http://fvue.nl/wiki/Bash%3a_Why_use_eval_with_variable_expansion? – dgo.a Aug 23 '13 at 06:01
  • 1
    @dgo.a, glad I helped. I've included your resources in the answer. They have nice additions to the man page. But I put `man bash` on first place so users don't forget to look what's supported by their particular bash version. – akostadinov Aug 23 '13 at 10:13