简体   繁体   中英

Cannot run .sh script under sudo in linux

I have a script foo.sh located in /home/pi/Documents/Python directory. Purpose of this shell script is to run python script which needs root priviledges as it must reset usb device.

The script is as follows:

#!/bin/sh
export PATH="$PATH:/home/pi/.local/lib/python3.7"
python3 /home/pi/Documents/Python/foo.py

When I run the foo.py from Midnight Commander (setting a cursor on the file and pressing enter) it works, it exports the path correctly and the python script fails as it does not have enough priviledges to reset usb device. I have actually made this script to run python script under root, but the root needs set a path to used module first. However when I run

sudo foo.sh

I receive an answer:

sudo: foo.sh: command not found

I have checked the permissions and the foo.sh file has -rwxr-xr-x

sudo python3 

typed in terminal also works correctly and opens python interpreter.

What is the problem that causes wrong behaviour under sudo?

Unless foo.sh is in a directory shown referenced by the PATH environmental variable, the environment will not recognise the command and hence the error

If you are in the directory with the foo.sh script, execute it with:

sudo ./foo.sh

If you are in a different directory, execute with:

sudo /pathtosh/foo.sh

I might be mistaken (I don't have a Linux Machine at hand atm, so I cannot verify), but if I recall correctly the user_home is part of the PATH variable exported for that user. When you use the command sudo you are acting on the behalf of root which has got a different user_home than yours (== the current user), therefore your script is not found in any of the directories listed in the active PATH (the one of root because you are using the sudo command).

However, it should be possible to run successfully the following command:

  $ sudo ./foo.sh

I hope this might shed some light.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM