Run sudo command within directory
Solution 1
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
Solution 2
For me a combination of sudo
and screen
worked out:
sudo -iu vagrant screen -mS npm_install bash -c 'cd /vagrant && npm install'
This command first switches to the vagrant
user. Then as vagrant
changes the directory to /vagrant
and executes npm install
.
Related videos on Youtube
Andrew Onischuk
Updated on September 18, 2022Comments
-
Andrew Onischuk over 1 year
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.
-
Andrew Onischuk over 9 yearsThe first approach I cannot use to set pwd in general case. (Added the bigger picture to the question) The second doesnt work for me since, it is not configured as you said (in general case for the user of our software)
-
gertvdijk over 9 years@AndrewOnischuk yes, second approach doesn't work, you're right. removed it.
-
Andrew Onischuk over 9 yearsThat actually works with -i specified sudo -i PWD=/root ls, thanks. Exactly what I was looking for
-
sffc about 8 yearsA practical use case is when you need to run "make install" in a directory you don't own, e.g., in the home directory of an unprivileged user. (The alternative in that case would be to use
sudo make -C ~unprivileged/project install
.) -
Yordan Georgiev over 4 years