Search code examples
bashubuntupermissionsenvironment

How to write in /etc/profile using bash | Permission Denied


I'm creating a bash script to set up an Ubuntu 16.04 lts OS to download, install and other stuff without introduce each command separately and I have to write in the /etc/profile file to add a PATH environment variable. When my code get into that line it appears the Permission Denied message, this is what I have:

sudo echo "export PATH=$PATH:/usr/local/go/bin" >> /etc/profile
bash: /etc/profile: Permission denied

Do you know how could I solve this?


Solution

  • Shell i/o redirection happens before the shell executes your command...in other words, when you write:

    sudo somecommand >> /etc/profile
    

    The >> /etc/profile part is performed as the current user, not as root. That's why you're getting the "permission denied" message. There are various ways of solving this. You can run:

    sudo sh -c "echo export PATH=$PATH:/usr/local/go/bin >> /etc/profile"
    

    Or you can take advantage of the append (-a) flag to the tee command:

    echo "export PATH=$PATH:/usr/local/go/bin" | sudo tee -a /etc/profile