A Safer Way to Return the Current Username in Shell Script
Getting the current username, it sounds like a very easy task:
|
|
But depending on the environment variable is not reliable, it can be easily overridden:
|
|
Or just simply fail to work:
|
|
The USER
environment was not set in /etc/profile
in this case:
|
|
This is especially important when writing shell script. You do not want to end up with a wrong username.
One solution is to use whoami
, which prints the effective user:
|
|
Another solution is to use id
command:
|
|
This will eliminate the overridden environment variable issue. Also, check out this StackOverflow post for others and POSIX compatible means:
https://stackoverflow.com/questions/19306771/get-current-users-username-in-bash