How to append text to a file when using sudo command on Linux or Unix

Originally published at: https://www.cyberciti.biz/faq/sudo-append-data-text-to-file-on-linux-unix-macos/

I am trying to add entry to /etc/hosts file using ‘sudo echo ‘192.168.1.254 router’ >> /etc/hosts’ but getting an error that read as, -bash: /etc/hosts: Permission denied. How do I insert or append text to a file when running sudo command on Linux or Unix-like system?

I suggest:

sudo bash -c 'echo whatyouneed >> /etc/hosts '

In this way the sudo gives privilege to bash command, which will execute what passed to it by -c switch.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki