In a shell script, my understanding is that "$@"
expands to the script arguments, quoting them as needed. For instance this forwards the script arguments to gcc:
gcc -fPIC "$@"
When using the bash pass-to-stdin syntax <<<
though, "@$"
doesn't work as I would expect it to.
#!/bin/bash
cat <<< "$@"
Calling the script as ./test.sh foo "bar baz"
gives
foo bar baz
I would expect
foo "bar baz"
Is there a way to write a shell script that prints it's arguments as you would write them on the shell prompt? For instance: a hint as to what command to use next, including the script arguments in the hint.
Best Answer
Well,
"$@"
expands to the list of positional parameters, one argument per positional parameter.When you do:
cmd
is being invoked with those 3 arguments: the empty string,foo bar
andblah<newline>blah
. The shell will call theexecve()
system call with something like:If you want to reconstruct a shell command line (that is code in the shell language) that would reproduce that same invocation, you could do something like:
Or with
zsh
, asking for different types of quotes:Or with
zsh
,bash
orksh93
(here forbash
, YMMV with other shells):You could also use the shell's xtrace option that causes the shell to print what it's going to execute:
Above, we ran the
:
no-op command withcmd
and the positional parameters as argument. My shell printed them in a nice quoted fashion suitable for reinput to the shell. Not all shells do that.