Javier Salas
Javier Salas

Reputation: 1188

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?

Upvotes: 10

Views: 18631

Answers (2)

oviniciusfeitosa
oviniciusfeitosa

Reputation: 1065

sudo sh -c "echo MY_GLOBAL_ENV_TO_MY_CURRENT_DIR=$(pwd)" >> /etc/environment"

Upvotes: 1

larsks
larsks

Reputation: 311740

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

Upvotes: 23

Related Questions