You can't; changing the directory is part of what sudo -i
does. But you can just go back to where you were and then run the command:
sudo -i sh -c "cd '$PWD'; ./myscript.sh"
That will fail if $PWD
contains single quotes. (On the other hand, if you know $PWD
doesn't contain whitespace, or anything special to the shell, you could nix the single quotes too.)
A safer way would be something like below:
sudo -i sh -c 'cd "${1}"; ./myscript.sh' sh "$PWD"
(A plain "$1"
doesn't work as you'd expect, because sudo -i
runs the user's login shell in between, leading to another round of expansions. It tries to escape the command to prevent those expansions, but fails for $1
(and $foo
etc.). See "sh -c" does not expand positional parameters, if I run it from "sudo --login". Is there a way around this? for the gory details.)
In any case, if that script is a tool commonly run by root, it would make sense to put it in some directory that's both in PATH
for root, and only writable by root
. In general, it's best to avoid any chance of non-root users messing up with what root
runs, though if it's e.g. in your regular account's home directory, the possible issues are likely minimal.
-i
? Why can't you just runsudo ./myscript
?sudo
andsudo -i
have different env, and it needs the env ofsudo -i
sudo -i
like that doesn't make much sense, so we need to understand why you think that is the solution. Can't you just runsudo -i /home/user/myscript.sh
? More importantly, why would you need root's login environment?