Run root Commands in Linux (Ubuntu) Without Password

Terminal Windows

Terminal Windows

Recently a student of mine asked me about running sudo commands in a shell script without prompting for the password. I thought finding the solution would be as easy as typing the question in Google and reading the first result returned. But that was not the case.

The following steps will help you achieve the desired output:

  1. Create a new script file (replace with your desired script name):
    vim ~/

    The script will be created in the user’s home directory

  2. Add some commands that only a root or sudo user can execute like creating a folder at the root directory level:
    mkdir /abc

    Note:Don’t add sudo to these commands. Save and exit (using :wq!)

  3. Assign execute permissions to it using:
    sudo chmod u+x
  4. Make changes so that this script doesn’t require a password.
    1. Open the sudoers file:
      sudo vim /etc/sudoers
    2. Add the following line at the end:
      ahmad ALL=(root) NOPASSWD: /home/ahmad/

      Replace ahmad with whatever your username is. Also make sure this is the last line. Save and exit.

  5. Now when running the command add sudo before it like:
    sudo ./

    This will run the commands inside the script file without asking for a password.

Note: Only the script file mentioned in the sudoers file is exempted from asking a password. The rest will behave as usual.