Search code examples
linuxbashsolarisswitch-user

Switch user and output variable contents


I am writing a bash script and want to switch to another user, cd into a directory specified by MYDIR in the users bash_profile and list the contents.

Currently I have:

read username
su - app${username} -c ls $MYDIR

The output is nothing, my first guess is that it is a problem reading $MYDIR from the users profile as doing it manually works fine e.g.

#su - appadmin
#ls $MYDIR

Solution

  • You need to quote the command to be executed.

    At the moment the shell is replacing $MYDIR with the value from the caller's environment. Also -c only passes the next arg to be executed, i.e. ls without the $MYDIR - you need to put quotes around the whole remote command:

    su - app${username} -c 'ls $MYDIR'