I was always thinking that to execute commands with sudo and to execute bash script with sudo were the same. But today I find that they are different. Here is what I've tested:

me@my_machine:~$ sudo echo $(whoami)

I execute the command from terminal and get the output: me. After reading this link: https://superuser.com/questions/384544/why-does-sudo-u-root-echo-whoami-not-return-root, I understand this.

Then I create a bash script named test.sh:

#!/usr/bin/env bash
echo $(whoami)

And I execute this script: sudo ./test.sh, to my surprise, the output now becomes: root.

So executing commands with sudo and executing Bash scripts with sudo are different?

If I have s Bash script, containing the command whoami, have it be executed with sudo, how could I get me, instead of root?


For the shell to run the command

sudo echo $(whoami)

it must first figure out what arguments to call sudo with. echo is just a simple string, so the shell does nothing to it, but $(whoami) is a command substitution that needs to be expanded. It does this by executing whoami and replacing the command substitution with its output. It is then ready to call sudo.

This means that sudo will be executed with echo and the output of whoami (which was executed as your unprivileged user) as arguments.

If you want to run whoami with sudo, you can put it in a script and run the script with sudo, as you've done, or you may use

sudo sh -c 'echo "$(whoami)"'

Here, the sh -c script is run as root, so whoami will also run as root.

The point is that the shell that runs whoami is executing as the root user.

The shell that executes whoami in the first command, sudo echo $(whoami), runs as your ordinary user, not root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.