Difference when using backticks in double quotes and single quotes in Bash

12

3

Why to the following two executions differ in output? (I need double quotes for variables in my eventual command)

$ sudo su -c "echo `cat /root/root_file`"
cat: /root/root_file: Permission denied
$ sudo su -c 'echo `cat /root/root_file`'
Yay, highly classified content!

Ambidex

Posted 2015-02-06T14:42:33.273

Reputation: 375

Answers

19

Bash performs a series of expansions before the command is executed (sudo in this case). In the first case, the command substitution is performed because it's in double quotes -- it executes as you, hence the error. In the second case, the single quotes prevent expansions, so the backticks are not substituted until root's shell is running.

See also https://www.gnu.org/software/bash/manual/bashref.html#Quoting

glenn jackman

Posted 2015-02-06T14:42:33.273

Reputation: 18 546

6

In the first example the backticks are evaluated by your shell (as you and not root). Try with

sudo su -c "echo `whoami`"

In the second one with the single quotes ' the whole string echo `cat /root/root_file` is passed to the root shell.

Matteo

Posted 2015-02-06T14:42:33.273

Reputation: 6 553