4

I'm working on some installation script in bash (on a Raspberry Pi running Stretch). It will copy files to /usr/local/bin and to my user profile and it will install a few packages if needed. The script is almost 2000 lines and 20–30 commands need root.

Now my question is: should I run the entire script with sudo or just as standard user and sudo only the commands inside the script that need admin rights?

  • If you sure that your script is completely right and it correctly handles exception events, you can freely you sudo to entire one. But from good security practice side and Unix ideology, you must use min permissions as much as possible and upper it only in cases when it's needed. – Yurij Goncharuk May 14 '18 at 19:27
2

If you know for sure that running the script with sudo won't do you any harm (For example, it won't create new files that will now need root privileges, but wouldn't otherwise), you should run it with sudo.

If you know there are some side effects or you are unsure, do it the safe way and use sudo just where you must.

  • Until now I run it as root, setting appropriate permissions for the logged on user. This works fine, but I still doubt if this is the way to go. – SBF May 20 '18 at 8:33
1

At the header of script put this:

#!/bin/bash

#Detects if script are not running as root... 
if [ "$UID" != "0" ]; then
   #$0 is the script itself (or the command used to call it)...
   #$* parameters...
   if whereis sudo &>/dev/null; then
     echo "Please type the sudo password for the user $USER"
     sudo $0 $*
     exit
   else
     echo "Sudo not found. You will need to run this script as root."
     exit
   fi 
fi
  • I know it's unsafe, but on raspberry pi, root has no password. So I get the question to enter the sudo password and just proceeds. Is there a way to detect if a password is set, just to skip the question? – SBF May 20 '18 at 8:27
  • Hmmm sudo password is not root password, is your user without password or really is root without password? Are you using sudo or su to login as root? – Luciano Andress Martini May 22 '18 at 11:40
  • I login with user pi (with password) - sudo doesn't require password. – SBF May 22 '18 at 11:48
  • Are you saying that it requests a password for you but you just need to press ENTER? – Luciano Andress Martini May 22 '18 at 11:51
  • Hello? Are you there? – Luciano Andress Martini May 22 '18 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.