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 $USER
bytecommander
$ sudo echo $USER
bytecommander
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
:
$ whoami
bytecommander
$ sudo whoami
root
$ id -un
bytecommander
$ sudo id -un
root
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)folder
cd /path/to/$(id -un)folder
%username%
mean? I guess it's some sort of Windows thing, but don't assume we'll know what it is. We're Linux people here, and most of us know very little about Windows. Please edit your question and explain what you need.