Search code examples
macosshellsudosu

Running a login shell using sudo inside a shell script on Mac OSX


I am trying to run some bash scripts that we wrote on Linux on Mac OS X Mountain Lion. The script performs a

#!/bin/bash
sudo su -l <username>  << EOF
echo $HOME
#execute command that is only on the path of <username>
EOF

No I am running the script as user1 and I am in the script trying to switch to user2. I actually need it to run like this as there are other portions that need to run as user1.

On linux I get

/home/user2

On Mac OS X I get

/Users/user1

So its not actually performing a login and as such any script that relies on us being logged in as user2 then fails as it doesn't reference either .bash_profile/.bashrc for user2

Been struggling with this for a while now and it seems as if there is now way to get OS X to behave in the same way as linux does.


Solution

  • Your shell is interpreting the $HOME variable in the heredoc, before the input reaches the su shell. You need to escape the $:

    bash-3.2$ sudo su -l root <<EOF
    > echo $HOME
    > echo \$HOME
    > EOF
    /Users/kevin
    /var/root
    

    The real question is why does it work on your Linux box.