17

I would like to create an alias that does something like this:

alias userYYY='sudo su userYYY; cd /a/path/that/only/userYYY/has/access'

So then from my command line, I am logged in with a sudo user, and I would like to type the alias userYYY so that my shell is now logged with userYYY and pwd is /a/path/that/only/userYYY/has/access.

How can I do that? This userYYY is for running some processes, and there must be anything in its home. Hence, I tried changing its $HOME using:

sudo usermod -m -d /a/path/that/only/userYYY/has/access userYYY 

And then from my shell with my sudoer file I did sudo su userYYY. But that didn't work. The only that worked was sudo su -l userYYYY but that opened a new bash inside my original shell (-bash-4.1$ ....).

In summary, what I want is to simply avoid having to write 2 lines in my shell:

sudo su userYYY
cd /a/path/that/only/userYYY/has/access

Any ideas?

5 Answers 5

13
alias userYYY='sudo su userYYY -c "cd /a/path/that/only/userYYY/has/access; /bin/bash"'
4
  • seems to work fine, but not sure how to remove this error, or if its an issue. using ubuntu 14.04LTS, noticed there was an issue with on debian... bash: cannot set terminal process group (13964): Inappropriate ioctl for device\nbash: no job control in this shell
    – sonjz
    Commented Feb 24, 2015 at 21:22
  • 2
    actually, after using it for a while, i noticed that the terminal gets killed pretty frequently using this method (disconnect around 15-30 min, regularly, my terminal lasts around 6hrs before disconnect)
    – sonjz
    Commented Feb 25, 2015 at 20:19
  • 1
    Just dug up this, this behaviour is due to a security fix: unix.stackexchange.com/questions/65843/…
    – sonjz
    Commented Feb 25, 2015 at 20:34
  • this has helped me edit my .bashrc file to sudo then cd where as having 2 separate lines just wasn't working.
    – RozzA
    Commented Feb 6, 2019 at 1:41
7

One option would be to edit ~/.bashrc of the target user, and add cd there:

cd /a/path/that/only/userYYY/has/access
1

I know this is slightly different than the original question, but the idea is to run the command as a different user without typing in a password when policy prohibits sudo su <user> -c.

sudo -u userYYY -- sh -c "cd /a/path/that/only/userYYY/has/access; /bin/bash"
0

Short answer - you can't. The sudo su starts a new shell which must exit before it gets to the cd command.

0

For me a combination of sudo and screen worked out:

sudo -iu vagrant screen -mS npm_install bash -c 'cd /vagrant && npm install'

This command first switches to the vagrant user. Then as vagrant changes the directory to /vagrant and executes npm install.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .