Possible solutions could be:
-
Starting interactive session.
sudo -s <<< "cd dir ; command"
or
sudo /bin/bash -c "cd dir ; command"
But I don't have /bin/bash /bin/sh /bin/su or other sudoer permissions
-
Changing directory before sudo is done.
cd dir ; sudo command
But I don't have permission to enter the dir.
-
I need a general case pwd set (like Popen cwd), so below is not answer I can use:
sudo command /path/to/file
What I'm trying to write is python Popen wrapper with sudo=True/False option, and currently I'm trying to somehow get cwd parameter to work.
Best Answer
I'm not sure what the bigger picture is, but your approach should be to run the command with on a file in the directory. E.g. if you want to run
grep regex file
wherefile
is in/root
, then you should approach it like this:And not:
Why this output? Well, it's shell syntax and sudo isn't running the command in another interactive shell.
Another approach would be to alter the environment variable
PWD
, like this: