How to execute a bash script that requires root privileges

bashrootscriptterminal

I have this script lines from my ISP:

sudo bash
echo "plugin L2TP.ppp">>/etc/ppp/options 
echo "l2tpnoipsec">>/etc/ppp/options

It works if I paste line by line into Terminal.
I want to create a *.command file and run it by double-clicking. But all I get is password prompting and then empty bash window. The resulting "options" file is empty.

I tried this:

#!/bin/bash

echo "plugin L2TP.ppp">>/etc/ppp/options 
echo "l2tpnoipsec">>/etc/ppp/options

I get:

/etc/ppp/options: Permission denied

I think I need to use some command to get root privileges from inside bash.

Best Answer

Take the script that you created:

#!/bin/bash

echo "plugin L2TP.ppp">>/etc/ppp/options 
echo "l2tpnoipsec">>/etc/ppp/options

Save it in your home directory, or a 'scripts' directory inside your home directory, as l2tp.sh. Allow it to be executed(write this command in Terminal):

chmod 700 ~/path/to/l2tp.sh

To execute the file using sudo (root privileges):

Method #1. In Terminal type:

$ sudo ~/path/to/l2tp.sh

Method #2. Create a file run_l2tp.command with this contents:

sudo ~/path/to/l2tp.sh

Allow it to be executed:

chmod u+x run_l2tp.command

When you double-click run_l2tp.command and enter the password the l2tp.sh file will be executed with root privileges.

Some notes:

  • On UNIX like systems, ~ is short for "my home directory".
  • Chmod 700 will make the file executable only by you. For more information: see this Wikipedia page.
  • typing 'sudo' before a command will execute the program using root privileges. Be careful when doing this, bad things can happen if you're not sure what you're doing.
  • Obviously you can omit the /path/to if you saved this script directly in your home directory.