How does bash deal with nested quotes?

user1833028 picture user1833028 · Sep 19, 2014 · Viewed 23.2k times · Source

I need to run a command with a syntax like this:
runuser -l userNameHere -c '/path/to/command arg1 arg2'

Unfortunately, I have to nest additional ' characters into the command itself and I can't tell bash to interpret these correctly. The command I would like to run is actually:

runuser -l miner -c 'screen -S Mine -p 0 -X eval 'stuff "pwd"\015''

Unfortunately, bash seems to be hitting the second ' and puking. This is the error:
-bash: screen -S Mine -p 0 -X eval stuff: No such file or directory, so obviously it's not getting past the '.

How can I nest this as one command? Thank you!

Answer

chepner picture chepner · Sep 19, 2014

You can use another type of quoting supported by bash, $'...'. This can contain escaped single quotes.

runuser -l miner $'screen -S Mine -p 0 -X eval \'stuff "pwd"\015\''

Note that within $'...', the \015 will be treated replaced with the actual ASCII character at codepoint 015, so if that's not what you want, you'll need to escape the backslash as well.

runuser -l miner $'screen -S Mine -p 0 -X eval \'stuff "pwd"\\015\''

I think you can take advantage of the $'...' to remove the need for eval as well:

runuser -l miner $'screen -S Mine -p 0 -X stuff "pwd"\015'