views:

53

answers:

2

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
+1  A: 

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'
martin clayton
Thats great, thanks for the explanation.
kerchingo
A: 

Change $MYDIR to ${MYDIR:?}. This will cause an error if MYDIR isn't set. It's possible that you are not exporting the variable in the profile, which is why it works in the command line, but not the script.

brianegge