1

Trying to do imbricated escape and that doesn't work obviously. My parameter with space is customer and its value is NAME WITH SPACE.

chroot /sites/FOLDER1 /bin/su FOLDER2 -c "/data/batch/myScript.sh -v -g -action params -customer NAME WITH SPACE"

I'm getting:

Error : Unknown parameter WITH

I read a few threads on the subjects but can't make out a solution : https://superuser.com/questions/360966/how-do-i-use-a-bash-variable-string-containing-quotes-in-a-command http://mywiki.wooledge.org/BashFAQ/050

Tried with single and double quote, with storing the param in a variable etc but no dice.

If I use

chroot /sites/FOLDER1 /bin/su FOLDER2 -c '/data/batch/myScript.sh -v -g -action params -customer 'NAME WITH SPACE''

It works a little better as I do not get the unknown parameter but it only takes NAME as parameter and ignore what is after the space

1 Answer 1

3

su -c "script-text" launches a separate shell interpreter which parses script-text as code. Consequently, that text needs to be escaped in an eval-safe manner. printf '%q' does this for bash (and will be entirely robust if your /bin/sh is a symlink to bash).

That is:

printf -v cmd '%q ' /data/batch/myScript.sh -v -g -action params -customer "NAME WITH SPACE"
chroot /sites/FOLDER1 /bin/su FOLDER2 -c "$cmd"

If your /bin/sh is not provided by bash, then you should consider an alternative implementation generating purely POSIX-compliant output, such as that provided by the Python pipes.quote() library function:

pyquote() {
  python -c 'import pipes, sys; print " ".join(pipes.quote(a) for a in sys.argv[1:])' "$@"
}

cmd=$(pyquote /data/batch/myScript.sh -v -g -action params -customer "NAME WITH SPACE")
chroot /sites/FOLDER1 /bin/su FOLDER2 -c "$cmd"
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I still get Unknown parameter WITH
declare -- cmd="/data/batch/myScript.sh -v -g -action params -customer NAME\\ WITH\\ SPACE "
Yes chroot /sites/FOLDER1 /bin/su FOLDER2 -c "$cmd"
To summarize from chat: There was a bug in myScript.sh, using $* rather than "$@" to iterate over arguments; with that fixed, the given solution now functions correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.