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
andid -un
:$ whoamibytecommander$ sudo whoamiroot$ id -unbytecommander$ sudo id -unroot
More information about those commands can be found by typing
man whoami
andman 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