Bash Alias – Switch user and go to switched user’s home directory

This one was a puzzle to solve. I wanted to create an alias so I can do the two things:
1. Switch to user automation
2. Go to automation’s home directory

I started by creating the following alias:

sa() {
    sudo su automation
    cd /home/automation

But this didn’t work and here’s the explanation.
After the first command “sudo su automation” is executed, the shell is now running as automation and the “cd /home/automation/” will be placed in the original user’s queue. After you exit user automation, the cd command will be picked from the queue and get executed. Therefore, I had to modify the alias to the following:

sa() {
    cd /home/automation
    sudo su automation
    cd ~

This time around, I am navigating to automation’s home directory first and then switching my user so I am already in the directory when I switch to the new user. The last command “cd ~” will be put in queue after “sudo su automation” is executed. And when I exit from automation, the “cd ~” will be executed from the queue and I will end up being in /home/varun.verma after I exit automation.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s