Run sudo command within directory
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
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
.