Quantcast
Viewing latest article 2
Browse Latest Browse All 5

Answer by Byte Commander for Environment Variable for Username

There might be a caveat if you plan to read the $USER environment variable in a command starting with sudo.

Bash variable expansion takes place before executing sudo to switch users, that means the $USER variable gets read from the current environment before sudo switches to root.

$ echo $USERbytecommander$ sudo echo $USERbytecommander

If this is not intended and you require a method that will return the name of the user as whom it really runs (normally "root"), you have at least three options to achieve that:

  • Run a bash interpreter as root and pass it the command which contains $USER. You must make sure that the command is enclosed with single quotes to prevent the current Bash interpreter from doing the variable expansion:

    sudo bash -c 'echo $USER'
  • Use a command output instead of the $USER environment variable.

    There are mainly two commands which would be useful here, whoami and id -un:

    $ whoamibytecommander$ sudo whoamiroot$ id -unbytecommander$ sudo id -unroot

    More information about those commands can be found by typing man whoami and man id.

You can use these commands like a variable and embed them into a string (e.g. a directory path) like this, using Bash's command substitution syntax. Here are two examples which cd into a directory named after the current user:

cd /path/to/$(whoami)foldercd /path/to/$(id -un)folder

Viewing latest article 2
Browse Latest Browse All 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>