35

I am making a bash script that will print and pass complex arguments to another external program.

./script -m root@hostname,root@hostname -o -q -- 'uptime ; uname -a'

How do I print the raw arguments as such:

-m root@hostname,root@hostname -o -q -- 'uptime ; uname -a'

Using $@ and $* removes the single quotes around uptime ; uname -a which could cause undesired results. My script does not need to parse each argument. I just need to print / log the argument string and pass them to another program exactly how they are given.

I know I can escape the quotes with something like "'uptime ; uname -a'" but I cannot guarantee the user will do that.

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400
aus
  • 1,294
  • 1
  • 14
  • 19
  • 1
    Can't gurantee that the user will escape the quotes. – aus May 31 '12 at 15:06
  • According to this answer: https://unix.stackexchange.com/a/472593/341661, although `echo $@` doesn't print out the quotes, $@ does "pass the quotes in background". I've tried this by writing 2 script: the 1st script passed "$@" to 2nd script, while the 2nd script prints "$1", and it worked – Nikolas Mar 03 '20 at 02:39
  • See also https://stackoverflow.com/questions/11456403/stop-shell-wildcard-character-expansion which asks more specifically about disabling `*` expansion (you can't do that either). – tripleee Aug 26 '21 at 09:36

7 Answers7

36

The quotes are removed before the arguments are passed to your script, so it's too late to preserve them. What you can do is preserve their effect when passing the arguments to the inner command, and reconstruct an equivalent quoted/escaped version of the arguments for printing.

For passing the arguments to the inner command "$@" -- with the double-quotes, $@ preserves the original word breaks, meaning that the inner command receives exactly the same argument list that your script did.

For printing, you can use the %q format in bash's printf command to reconstruct the quoting. Note that this won't always reconstruct the original quoting, but will construct an equivalent quoted/escaped string. For example, if you passed the argument 'uptime ; uname -a' it might print uptime\ \;\ uname\ -a or "uptime ; uname -a" or any other equivalent (see @William Pursell's answer for similar examples).

Here's an example of using these:

printf "Running command:"
printf " %q" innercmd "$@" # note the space before %q -- this inserts spaces between arguments
printf "\n"
innercmd "$@"

If you have bash version 4.4 or later, you can use the @Q modifier on parameter expansions to add quoting. This tends to prefer using single-quotes (as opposed to printf %q's preference for escapes). You can combine this with $* to get a reasonable result:

echo "Running command: innercmd ${*@Q}"
innercmd "$@"

Note that $* mashes all arguments together into a single string with whitespace between them, which is normally not useful, but in this case each argument is individually quoted so the result is actually what you (probably) want. (Well, unless you changed IFS, in which case the "whitespace" between arguments will be the first character of $IFS, which may not be what you want.)

Gordon Davisson
  • 107,068
  • 14
  • 108
  • 138
6

If the user invokes your command as:

./script 'foo'

the first argument given to the script is the string foo without the quotes. There is no way for your script to differentiate between that and any of the other methods by which it could get foo as an argument (eg ./script $(echo foo) or ./script foo or ./script "foo" or ./script \f\o""''""o).

William Pursell
  • 190,037
  • 45
  • 260
  • 285
  • Interesting. Guess I am out of luck for printing, but it seems that passing `"$@"` will still allow the external program to parse the args correctly. – aus May 31 '12 at 15:19
4

If you want to print the argument list as close as possible to what the user probably entered:

#!/bin/bash
chars='[ !"#$&()*,;<>?\^`{|}]'
for arg
do
    if [[ $arg == *"'"* ]]
    then
        arg=\""$arg"\"
    elif [[ $arg == *$chars* ]]
    then
        arg="'$arg'"
    fi
    allargs+=("$arg")    # ${allargs[@]} is to be used only for printing
done
printf '%s\n' "${allargs[*]}"

It's not perfect. An argument like ''\''"' is more difficult to accommodate than is justified.

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400
Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429
3

Use ${@@Q} for a simple solution. To test put the lines below in a script bigQ.

#!/bin/bash
line="${@@Q}"
echo $line

./bigQ 1 a "4 5" b="6 7 8"
'1' 'a' '4 5' 'b=6 7 8'
flick
  • 41
  • 2
  • ```@Q``` is an expansion operation that stands for "The expansion is a string that is the value of parameter quoted in a format that can be reused as input." https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html – rodvlopes Jun 23 '21 at 13:16
  • 1
    The `@Q` expansion operator is Bash 4+ only, and will not work e.g. on MacOS which is still stuck on Bash 3. – tripleee Aug 26 '21 at 09:35
1

As someone else already mentioned, when you access the arguments inside of your script, it's too late to know which arguments were quote when it was called. However, you can re-quote the arguments that contain spaces or other special characters that would need to be quoted to be passed as parameters.

Here is a Bash implementation based on Python's shlex.quote(s) that does just that:

function quote() {
  declare -a params
  for param; do
    if [[ -z "${param}" || "${param}" =~ [^A-Za-z0-9_@%+=:,./-] ]]; then
      params+=("'${param//\'/\'\"\'\"\'}'")
    else
      params+=("${param}")
    fi
  done
  echo "${params[*]}"
}

Your example slightly changed to show empty arguments:

$ quote -m root@hostname,root@hostname -o -q -- 'uptime ; uname -a' ''
-m root@hostname,root@hostname -o -q -- 'uptime ; uname -a' ''
Helder Pereira
  • 5,130
  • 2
  • 30
  • 50
  • this does work in some cases, but fails in others. Almost, but not quite for my use case. – senorsmile Apr 16 '20 at 22:15
  • 1
    BTW, `function funcname() {` merges the POSIX sh syntax `funcname() {` and the legacy ksh syntax `function funcname {` in a way that's incompatible with *both* POSIX sh and legacy ksh, and for no benefit whatsoever. See https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Dec 30 '21 at 17:13
-2

Just separate each argument using quotes, and the nul character:

#! /bin/bash


sender () {
    printf '"%s"\0' "$@"
}


receiver () {
    readarray -d '' args < <(function "$@")
}


receiver "$@"

As commented by Charles Duffy.

-3

eval "./script -m root@hostname,root@hostname -o -q -- 'uptime ; uname -a'"

https://ss64.com/bash/eval.html

djg
  • 120
  • 6
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Nic3500 Jun 09 '20 at 05:02
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. I would recommend you to check SO's [official How to Answer article](https://stackoverflow.com/help/how-to-answer) along with the comprehensive [blog post](https://codeblog.jonskeet.uk/2009/02/17/answering-technical-questions-helpfully/) from [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet). – Aleksey Potapov Jun 09 '20 at 11:35
  • sounds like you are interested in overthinking simple answers – djg Dec 30 '20 at 08:34
  • Simple? It's a _wrong_ answer on its face; it's doing the opposite of what the OP asked for (they want `./script` to be able to recover its original argument list; this simply doesn't do anything like that). If you want to argue that it is in fact right, you need to provide some explanation. – Charles Duffy Dec 30 '21 at 17:11