3

Hello I have to write a script with the name setip that can be run like this:

./setip <ip> <mask>

and that must set the IP address to <ip> and the mask to <mask> on the lo1 interface. Below is the content of my script, but it when I try to run it I get the error "permission denied". What is wrong with my script and how should I proceed ?

#! /bin/bash
sudo echo 
"
auto lo:1
iface lo:1 inet static
address $1
netmask $2" >/etc/network/interfaces
rares985
  • 133

3 Answers3

3
sudo echo "  
auto lo:1  
iface lo:1 inet static  
address $1  
netmask $2" | sudo tee /etc/network/interfaces

The last line on your script netmask $2" >/etc/network/interfaces attempts to edit the interfaces file which only root can write to. (Or at least it should be owned by root)
However, sudo echo "" > likely does not work how you want it to.

What it's doing is it is executing echo "" with root permissions, but the > operator is not executing with those permissions.

You may want to reformat your command along the lines of this example. In this case, the command that outputs to the file is being run as root, while the other commands do not have to be. I've shown you an example of that above.

Robobenklein
  • 1,486
  • 16
  • 28
1

I don't think sudo is doing what you think it's doing. What's actually going on is that sudo is only affecting the echo command - it won't actually output what you need to the /etc/network/interfaces/ file because sudo doesn't actually cover the >.

So what can you do? You have two options:

  1. reformat your command to work like the one provided in the link from robobenklein in their answer.
  2. Run the entire script with sudo which would effectively run the entire command as superuser and the redirection might work.
Thomas Ward
  • 74,764
0

You need to run chmod +x setip to allow your script to be executable. More information on file permissions can be found here.

ShadowMitia
  • 995
  • 1
  • 7
  • 13