Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the current user's shell

Tags:

shell

I'm programming a .sh script that will, at some point, change the shell of the user to /bin/zsh. The command is of course the following:

chsh -s /bin/zsh

However this asks for the user's password, and I would like to only execute it if the current user's shell is not already /bin/zsh. For this I need a command that would let me know the current shell, and compare it with "/bin/zsh" or something alike. I found there's a c getusershell function, but isn't there a way to know this from a shell script?

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

like image 823
Ernesto Avatar asked Jun 05 '13 15:06

Ernesto


People also ask

How do I check my current Windows shell?

How do I check my current Windows shell? To get the name of the current shell, Use cat /proc/$$/cmdline . And the path to the shell executable by readlink /proc/$$/exe . $> echo $0 (Gives you the program name.

How do I find my current shell on Mac?

There's an easy way to tell — here's how. Open the Terminal application on your Mac. At the prompt, type echo $0 , as shown below.


3 Answers

You shouldn't assume /etc/passwd is the location where the user's shell is stored.

I would use this:

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

Edit: Note that getent is only implemented on Solaris, BSDs and GNU/Linux based OSes.

AIX, HP-UX and OS X have their own ways to do a similar thing (resp. lsusers -c, pwget -n and dscl ...) so this command should be enhanced should these OSes need to be supported.

like image 95
jlliagre Avatar answered Oct 22 '22 20:10

jlliagre


$SHELL returns the shell of the current user:

$ echo $SHELL
/bin/zsh
like image 16
Daniel Avatar answered Oct 22 '22 20:10

Daniel


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

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

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

This assumes /etc/passwd is locally complete (as opposed to being NIS served; see your /etc/nsswitch.conf and respective man page).

like image 2
Jens Avatar answered Oct 22 '22 19:10

Jens