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?

-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.