Ubuntu – Run sudo command within directory

bashcd-commandsudo

Possible solutions could be:

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

  2. Changing directory before sudo is done.

    cd dir ; sudo command
    

    But I don't have permission to enter the dir.

  3. 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 where file is in /root, then you should approach it like this:

$ sudo grep regex /root/file

And not:

$ sudo 'cd /root; grep regex file'
sudo: cd /root; grep regex file: command not found

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:

$ sudo -i PWD=/root grep regex file
Related Question