I am writing a program in Bash that needs to get the user\'s username.
I have heard of a thing called whoami, but I have no idea what it does or how to use it.
W
Get the current task's user_struct
#define get_current_user() \
({ \
struct user_struct *__u; \
const struct cred *__cred; \
__cred = current_cred(); \
__u = get_uid(__cred->user); \
__u; \
})
Use the standard Unix/Linux/BSD/MacOS command logname to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user's name and then exit. This command has been around since about 1981.
My-Mac:~ devin$ logname
devin
My-Mac:~ devin$ sudo logname
Password:
devin
My-Mac:~ devin$ sudo su -
My-Mac:~ root# logname
devin
My-Mac:~ root# echo $USER
root
Two commands:
id
prints the user id along with the groups.
Format: uid=usernumber(username) ...
whoami
gives the current user name
On most Linux systems, simply typing whoami on the command line provides the user ID.
However, on Solaris, you may have to determine the user ID, by determining the UID of the user logged-in through the command below.
echo $UID
Once the UID is known, find the user by matching the UID against the /etc/passwd
file.
cat /etc/passwd | cut -d":" -f1,3
For Bash, KornShell (ksh
), sh
, etc. Many of your questions are quickly answered by either:
man [function]
to get the documentation for the system you are using or usually more conveniently:
google "man function"
This may give different results for some things where Linux and Unix have modest differences.
For this question, just enter "whoami" in your shell.
To script it:
myvar=$(whoami)
In Solaris OS I used this command:
$ who am i # Remember to use it with space.
On Linux- Someone already answered this in comments.
$ whoami # Without space