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 ]
    echo "ERROR : Root Priveleges Required"                                                                                       
    exit NOT_ROOT                                                                                                                 


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
  • 1
    Better in which sense? Why not add sudo to the relevant commands and remove all those checks and give permissions to everybody? Also, service NetworkManager restart might be better than killing and manually starting. – muru Jan 18 '18 at 8:28
  • Sure, I will write Service NetworkManager restart instead . And also I don't exactly know in which sense. I just want to know If there are any cons and pros regarding performance, security or some other stuff that I don't know. – C0deDaedalus Jan 18 '18 at 8:36

I think your script can be condensed to:


sudo service network-manager restart || exit $NOT_ROOT
if service network-manager status
    echo "Successfully Restarted NetworkManager"
    echo "ERROR : Failed to work"
    exit 1

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.

  • I changed my script to what you suggested. It works awesome. Thanks ! – C0deDaedalus Jan 18 '18 at 8:48
  • /bin/bash is not needed here, /bin/sh would suffice. See wiki.ubuntu.com/DashAsBinSh for the differences. – Melebius Jan 18 '18 at 8:50

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.