0

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?

2
  • If you were to try to mechanically generate an arbitrarily nested set of commands, you would probably do so using double quotes alone, escaping and re-escaping double quotes and backslashes as you work you way from the innermost command outwards, rather than alternating single and double quotes. Commented Aug 24, 2021 at 21:56
  • @tmp : Note that string catenation in bash is done by simply writing the words to be catenated next to another, as in $x$y, which catenates the content of the variables x and y. Hence 'foo''bar' is just a different way of writing 'foobar', i.e. denoting the string foobar. Therefore, quotes can't nest, and if you want to have a quote inside a quoted string, you have to escape it - i.e. 'foo\'bar'. Commented Aug 25, 2021 at 6:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.