Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

When working on the command line, I often change to sudo using sudo -i. However, my working directory changes automatically to /root. I never want to go there; I want to stay where I was! How can I achieve this?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

You could use sudo -s instead, it would not change your current directory to /root, though some of your environment variables would not be those of root.

This page from the Ubuntu Forums has a nice summary:

Summary of the differences found   
                                               corrupted by user's 
                HOME=/root      uses root's PATH     env vars
sudo -i         Y               Y[2]                 N
sudo -s         N               Y[2]                 Y
sudo bash       N               Y[2]                 Y
sudo su         Y               N[1]                 Y

This page from from Ubuntu's documentation has much more background information on sudo.

share|improve this answer
    
Beautiful! Thanks a bunch, simple but great little overview! –  user Jun 13 '12 at 23:41
    
@user1162541 Happy to be able to help. –  Levon Jun 13 '12 at 23:42

If you want to use su, there is a way to stay in the same directory.

su - user -c "cd `pwd`; bash"

What’s going on here:

  • su - user = login as user
  • -c which means "run a command in the new user’s shell"
  • -c "cd `pwd`" the command we give is to switch to the current directory (`pwd`) – but because we use the backticks in double quotes, the pwd command is evaluated before we run the su command, so that we actually switch to the directory we’re in NOW as the old user.

    • By contrast, -c 'cd `pwd`' would execute the pwd command in the new shell, so this would evaluate to cd /root, which, of course, won’t accomplish anything.

    The only problem here is that the new shell exits right after running the command, so then we add:

  • -c "cd `pwd`; bash" which means "run bash (new shell) after running the cd command. The bash shell doesn’t exit until we log out of it.

Note that you can replace `pwd` with $(pwd).  They’re functionally the same, but the abundance of quote-like characters can become hard to read.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.