Linux – Changing the shell (using chsh) via the command line in a script

linuxshell

In a startup script that sets up a machine, I want to run

chsh -s /bin/zsh

However, this asks for the user's password. How do I pass in the password as a parameter? Or if I have sudo power, can I somehow bypass that step? Or alternatively, is there another way to change the default startup shell?

Best Answer

The following prevents locked-down accounts from changing their shells, and selectively lets people use chsh themselves WITHOUT sudo or su:

Simple setup that is still secure:

  1. Add this very top of /etc/pam.d/chsh:

    # This allows users of group chsh to change their shells without a password.
    #
    # Per: http://serverfault.com/questions/202468/changing-the-shell-using-chsh-via-the-command-line-in-a-script
    #
    auth       sufficient   pam_wheel.so trust group=chsh
    
  2. Create the chsh group:

    groupadd chsh
    

For any user allowed to change their shell:

    usermod -a -G chsh username

Money shot:

user@host:~$ getent passwd $USER
user:x:1000:1001::/home/user:/bin/bash
user@host:~$ chsh -s `which zsh`
user@host:~$ getent passwd $USER
user:x:1000:1001::/home/user:/usr/bin/zsh
user@host:~$