Execute command with sudo and execute Bash script with sudo

7,370

This answer explains what user executes the command substitution $(whoami) shown in the question. In actuality, the construct echo $(whoami) would hopefully never be used since whoami on its own would be the correct way of outputting the username of the current user.

Calling echo on a command substitution is simply not needed, and may even under some circumstances modify the output of the command in the command substitution. Don't use echo $(...).

Running whoami would output the username of the unprivileged user in the question, and sudo whoami would output 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 inside the command substitution with sudo, you can put it in a script and run the script with sudo, as you've done, or you may use an in-line script, as in

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.

Share:
7,370

Related videos on Youtube

Yves
Author by

Yves

Updated on September 18, 2022

Comments

  • Yves
    Yves over 1 year

    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: 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 a Bash script, containing the command whoami, have it be executed with sudo, how could I get me, instead of root?