How to deal with multiple quotes in one line bash command?

Issue

For example, if my goal is that run a one-line bash command like this,

sudo bash -c ' sudo bash -c '' sudo bash -c ''' echo ''''1234'''' ''' '' '

It doesn’t work.

Also I tried the 2nd commnad,

sudo bash -c ' sudo bash -c " sudo bash -c ''' echo ""1234"" ''' " '

Not work neither.

sudo bash -c ' sudo bash -c " echo '''123''' " '

the 3rd one, it indeed works, but it only has 3 levels at the top.

So, is there an actual way to get this command work with only quotes trick?

Solution

How to deal with multiple quotes in one line bash command?

Use functions, declare -f and printf "%q" to properly quote stuff. Don’t do it yourself.

# Function to run, just normally write stuff to execute.
work() {
    echo "1234"
}
# Script to run - contains work function definition and calls work.
script="$(declare -f work); work"
# bash -c "$script"
# quote it
script2="$(printf " %q" bash -c "$script")"
# bash -c "$script2"
# Well, no point, but an example, quote it again:
script3="$(printf " %q" bash -c "$script2")"
bash -c "$script3"
printf "%q " bash -c "$script3"

outputs:

1234
bash -c \ bash\ -c\ \\\ bash\\\ -c\\\ \\\$\\\'work\\\ \\\(\\\)\\\ \\\\n\\\{\\\ \\\\n\\\ \\\ \\\ \\\ echo\\\ \\\"1234\\\"\\\\n\\\}\\\;\\\ work\\\' 

You can copy the bash -c .... line to your terminal and execute it.

If you want different quotation style, you can use bash special ${var@Q} variable expansion or /bin/printf executable from coreutils.

Is there an actual way to get this command work with only quotes trick?

No. Quotes are grouped in pars, writing multiple quotes is useless and used for readability. In your example 'bash -c ''''1234''''' is just 'qouted stuff'unqouted stuff'quoted stuff'unqouted stuff' etc... Doing '''' changes nothing. You have to escape \' quotes to preserve literal meaning of them.

Answered By – KamilCuk

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published