Search code examples
bashsu

Creating a bash alias to su to a new user and source a script


I'd like to create a bash alias that does the following:

  • su to another user
  • cd to a certain directory
  • source another script (specifically a python virtualenv activation script)

After running the alias, I would like to be logged in as the user, in the directory, with the virtualenv activated. I can get everything to work except for the su, which seems to live in its own parallel universe.

I can't see a way to make the cd and source run inside the su environment and stick, leaving me able to continue work inside the su environment. (e.g. su -c just runs the operations and leaves me where I started.)

UPDATE:

To clarify a bit, I want something like this:

sudo -u www-data bash -c 'cd /var/www; pwd; whoami'

But I want to remain in the interactive subshell until I ^D out.


Solution

  • If you don't care about your ~/.bashrc, you can just source your file instead of that:

    su -c 'bash --rcfile myfile' 
    

    If you do care and your file only exports variables (i.e. doesn't define aliases or completion):

    su -c 'source myfile; bash'
    

    If you do need your ~/.bashrc and you need defined aliases and completion, you can source both with:

    su -s /bin/bash -c 'bash --rcfile <(echo "source ~/.bashrc; source myfile")'