Linux/Why does the su command run in CMD and not in script?

Linux/Why does the su command run in CMD and not in script? … here is a solution to the problem.

Linux/Why does the su command run in CMD and not in script?

I have the next script :

cd /home
touch $PF ; chown $NU.$NU $PF
su -p -s /bin/sh root -c "node"

When I run it, it throws the next error :

sh: node: command not found

But when I run it from the linux command line, it succeeds and gives me the node command line.

What could be the reason?

Solution

node may not be in the root user's $PATH.

I checked the su doc and noticed the following:

-m, -p, --preserve-environment
   Preserve the current environment, except for:

$PATH
       reset according to the /etc/login.defs options ENV_PATH or ENV_SUPATH (see below);
[...]
   ENV_PATH (string)
       If set, it will be used to define the PATH environment variable when a regular user login. The value can be
       preceded by PATH=, or a colon separated list of paths (for example /bin:/usr/bin). The default value is
       PATH=/bin:/usr/bin.

ENV_SUPATH (string)
       If set, it will be used to define the PATH environment variable when the superuser login. The value can be
       preceded by PATH=, or a colon separated list of paths (for example /sbin:/bin:/usr/sbin:/usr/bin). The default
       value is PATH=/sbin:/bin:/usr/sbin:/usr/bin.

So while you may have node in current $PATH, it may not be in root s $PATH

As some commenters have already mentioned, you can try to provide absolute $PATH for node:

su -p -s/bin/sh root -c "/path/to/node"

If you can call node from the current user, try which node to determine the full path to the executable.

You can also try echoing your $PATH.

su -p -s/bin/sh root -c 'echo $PATH'

Related Problems and Solutions