Sunday, 20 October 2019

bash - How to append text to the end of a file as root user?


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?



Answer



The redirection (>>) is done by the shell; your sudo affects echo only.


You can use this trick:


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

This way tee will append the text to the /output/file with proper permissions.


EDIT (answering comment): 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.


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...