There might be a caveat if you plan to read the
$USER environment variable in a command starting with
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 $USER
$ sudo echo $USER
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:
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,
$ sudo whoami
$ id -un
$ sudo id -un
More information about those commands can be found by typing
man whoami and
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/$(id -un)folder