sudo: node : command not found
No, sudo
does not preserve your $PATH
environment variable for security reasons. Instead, it gets replaced with a secure_path
defined in /etc/sudoers
, which you should not change.
$ sudo grep secure_path /etc/sudoers
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
You think to have verified that the $PATH
variable stays the same with your command
sudo echo $PATH
but actually Bash expands variables before starting to execute any (here the sudo
) command, which means the line above shows your own $PATH
value. To get the one as sudo
, use e.g.
sudo bash -c 'echo $PATH'
What you can do is to e.g. resolve the command you want to run (node
or npm
) in your own user's shell using process substitution with which
:
sudo "$(which npm)" install -g angular-cli
sudo "$(which node)" app.js
This first runs which npm
or which node
as your user, which returns the absolute path of the executables belonging to the specified commands. Then that output is literally inserted into your sudo
command, so sudo
actually believes it got executed with absolute paths like below, removing the need to look anything up in $PATH
:
sudo /home/dc/node/bin/npm install -g angular-cli
sudo /home/dc/node/bin/node app.js
You could just create a soft link for node, npm and npx in the /sbin directory e.g.
ln -s /usr/local/lib/nodejs/node-v12.14.1-linux-x64/bin/node /sbin/node
Syntax > ln -s (source) (destination)
Now running sudo node
should work