Define current user shell

I am programming a .sh script that at some point will change the user shell to / bin / zsh. Of course, the command:

chsh -s /bin/zsh 

However, this asks for the user password, and I would like to execute it only if the current user shell is no longer /bin/zsh . To do this, I need a command that tells me the current shell and compare it with "/bin/zsh" or something similar. I found the getusershell c function there, but there is no way to find out from the shell script?

Update: Sorry, I mean the shell that the user specified as his preferred shell. So yes, the one that is listed in /etc/passwd . The logic behind this is that the script is about to change the user's preferred shell as zsh, and I just want the script to check first if it is not zsh yet.

+7
source share
6 answers

$SHELL returns the shell of the current user:

 $ echo $SHELL /bin/zsh 
+14
source

You should not assume that /etc/passwd is where the user shell is stored.

I would use this:

 getent passwd $(id -un) | awk -F : '{print $NF}' 

Edit: note that getent is only available on Solaris, BSD, and GNU / Linux.

AIX, HP-UX, and OS X have their own ways of doing a similar thing (respectively lsusers -c , pwget -n and dscl ... ) so that this command is improved if these OSes need to be supported.

+4
source
 $ awk -F: '$1 == "myusername" {print $NF}' /etc/passwd /bin/zsh 

Or, if you have a username in the var shell variable:

 awk -F: -vu=$var '$1 == u {print $NF}' /etc/passwd 

This assumes that /etc/passwd is locally complete (unlike the NIS supported, see your /etc/nsswitch.conf and the corresponding manual page).

+2
source

The following command will give you the current shell (in the CMD cell):

 ps -p $$ 
+2
source

The following works:

 ps p $$ | awk '{print $5}' 

Sometimes $ SHELL and the values ​​in the / etc / passwd file are incorrect.

0
source
 perl -e '@pw = getpwuid $< ; print $pw[8], "\n"' 

This assumes that Perl is installed, configured correctly in your $PATH , which is a fairly safe bet on most modern Unix-like systems. (This is probably a safer bet than getent , or that the user's information is actually stored in the /etc/passwd or that the value of $SHELL not been changed.)

$< is the real UID of the current process. getpwuid() returns an array of values ​​from /etc/passwd or any other mechanism used by the system (NIS, LDAP). Element 8 of this array is the user's login shell.

The above may be slightly reduced to:

 perl -e 'print +(getpwuid $<)[8], "\n"' 

or

 perl -e 'print((getpwuid $<)[8], "\n")' 

The reasons for the unary + operator or extra parentheses are pretty obscure.

0
source

All Articles