Linux - use "su -" but keep the current directory

When I do su - to get to root, my current directory is set to root's home. Is there anyway to keep the current directory that I was in, much like sudo -s. Or is the answer to use sudo?


Solution 1:

It's always better to use sudo, if possible, because then you don't need to know (or give someone) root's password. Set the root password to something long and horrible and then lock it in a safe.

If you want to deny someone access later, you just remove their access to sudo, rather than having to teach everyone else a new root password.

However - you don't need to use the '-' parameter if you don't want to. You will get a shell as root, it will just not be a login shell (so it will not run root's .profile.)

Solution 2:

I agree that sudo is almost always a better answer but to answer the other part of the question...

The '-' in 'su -' indicates that you want to emulate a superuser login, rather than just run with superuser priviledges.

If you use plain 'su' rather than 'su -' you will stay in the same directory; however you will also be running in the same environment so may need to modify your path to access some admin commands.

Solution 3:

If you use su without the -, it should keep you in your current directory. -, -l or --login tell su to:

Provide an environment similar to what the user would expect had the user logged in directly.

Or just use sudo, it's got a lot of other advantages. Or ssh keys.

Solution 4:

If you really 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
  • -c which means "run a command in the new 's shell
  • -c "cd `pwd`" the command we give is to switch to the current direcotory (pwd) - but because we use the backticks, 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. 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 and the bash shell doesn't exit until we log out of it.