33

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.

4

7 回答 7

35

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.)

于 2012-05-31T15:05:29.480 回答
5

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).

于 2012-05-31T14:57:31.767 回答
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.

于 2012-05-31T16:02:45.590 回答
2

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'
于 2020-09-25T02:24:08.473 回答
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' ''
于 2020-03-24T20:51:13.830 回答
-1

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.

于 2022-01-06T22:37:28.780 回答
-2

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

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

于 2020-06-08T22:33:52.597 回答