Use sudo with echo in shell

You can’t use sudo directly with echo in shell scripts / command line, so you need to use tee with append (-a). For example (simplified script example to update /etc/hosts for localhost entries):

if [ $(cat /etc/hosts | egrep -c "\s$1") == 0 ]; then
	echo "127.0.0.1 $1" | sudo tee -a /etc/hosts
fi

Leave a Reply