Ubuntu – Modifying Permissions vs Root Script Execution. What’s Better

bashpermissionsscripts

After every suspend, When I wake up my laptop, it never connects to any network and have to restart NetworkManager again. So, out of laziness I wrote this script that works fine as expected.

I have used an if block to check that the script is always executed by the root user:

if [ $(id -u) -ne 0 ]
then
    echo "ERROR : Root Priveleges Required"                                                                                       
    exit NOT_ROOT                                                                                                                 

else                                                                                                                                  
    netrestart                                                                                                                
fi

And I gave this script this permission (being root when executing this command):

chmod u+x netrestart

Now, When I run this script as a non-root user, it shows this

bash: ./netrestart: Permission denied

And then, running script with sudo runs fine

sudo ./netrestart

I think that makes the root check in the script useless. Now I have 2 questions:

  1. Shall I remove that part of code or still use in the script?

  2. What's better and how?

    • Checking if user is root inside the script and giving execute permissions to everyone, i.e., chmod 755 netrestart
    • Setting the right needed permissions on script itself and not including the check for if user is root inside the script, i.e., chmod 711 netrestart

Best Answer

  • I think your script can be condensed to:

    #!/bin/bash
    
    NOT_ROOT=2
    sudo service network-manager restart || exit $NOT_ROOT
    if service network-manager status
    then
        echo "Successfully Restarted NetworkManager"
    else
        echo "ERROR : Failed to work"
        exit 1
    fi
    

    sudo will check for root access for you and prompt if necessary. The service ... status check will more reliably tell you if NetworkManager started up normally.

    You can grant this execute permissions on this script to everyone, and sudo will take care of permission checks.

  • Related Question