I see this question a lot in search engines requests which point to this blog. And if you're so interested how this is done, I'm happy to explain.
Standard shell environment variables pointing to user id
Not only in bash, but in any other shell on your system, there's quite a few standard environment variables set by default when you log in. Among them there are ones which contain your username, and so you can use them to find out the uid as well.
The variables I'm talking about are USER and USERNAME. Both of them should contain the same user name, in my example it's greys:
ubuntu:~$ echo $USER greys ubuntu:~$ echo $USERNAME greys
Knowing the username, it's very easy to use the id command to confirm the user id:
greys@ubuntu:~$ id -u greys
1000
Bash environment variables
In Bash specifically, there's also a few variables automatically set for your convenience so that you don't have to figure UID based on the username.
In fact, there are three variables which you will find useful:
- UID – your user ID
- EUID – your effective user ID
- GROUPS – array of all the Unix groups you belong to
Here is how to show the values of these variables:
ubuntu$ echo $UID 1000 ubuntu$ echo $EUID 1000 ubuntu$ echo $GROUPS 113
Flash_sh says
You can use also $UID, $EUID and $GROUPS in bash.
admin says
Thanks for the comment! I've just expanded the post.
Flash_sh says
There is also variable $LOGNAME filled with user name.
Only $USER and $LOGNAME is suitable for portable Born shell-like scripts (sh, ksh, bash, zsh). The $USER is known also in csh/tcsh.
You can see all groups by echo ${GROUPS[*]} or ${GROUPS[@]} (first item in array is primary group /use newgrp to change/)
Sorry for splitting into 2 posts.
Gleb Reys says
Thanks again!
My bash skills are a bit rusty, so it's a pleasure to receive pointers like this from someone who knows better 🙂
I'll be posting a whole article on Bash variables later on, and will be sure to include your comments.