2

So I'm trying to create a install script for my raspberries, first thing is to give them a static IP.

echo -e "Enter static IP"
read static_ip

echo -e "Enter DNS IP"
read dns_ip

echo -e ""
echo -e "The following settings will be set"

echo -e "\e[32mStatic IP:\e[0m\t${static_ip}"
echo -e "\e[32mDNS IP:\e[0m\t${dns_ip}"

sudo echo "interface wlan0" >> /etc/dhcpcd.conf
sudo echo "static ip_address=${static_ip}/24" >> /etc/dhcpcd.conf
sudo echo "static routers=${dns_ip}" >> /etc/dhcpcd.conf
sudo echo "static domain_name_servers=${dns_ip}" >> /etc/dhcpcd.conf

But it keeps saying "permission denied", I was wondering what I'm doing wrong here?

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
killstreet
  • 123
  • 6

2 Answers2

5

In sudo echo … >> … The redirection (>>) is set up by the shell before sudo is started. If echo was about to open the file by itself, it could; but it is about to start with stdout inherited from sudo, which in turn starts with stdin set up by the invoking shell. The error you got means the shell was denied access to the file.

Use sudo tee. The point is tee can open files by itself:

echo "something" | sudo tee -a /output/file > /dev/null

This way tee will append (-a) the text to the /output/file with proper permissions.

tee is designed to pass its input and duplicate it (in general: multiply). In this case one copy goes to the file and the other travels along the pipe. Since we only need the first one, we redirect the second copy to /dev/null so it doesn't appear in the console. Everything that goes to /dev/null vanishes.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
0

You need to run it in a subshell to make the redirection work.

sudo sh -c echo "string" >> file

[ from sudo man page: examples ]

Tom Cee
  • 11
  • 1
  • This won't work, the redirection is still parsed by the outer shell. You have to quote properly, like `sudo sh -c 'echo "string" >> file'`. – Kamil Maciorowski Jun 08 '17 at 19:22