sudo unable to write to /etc/profile [duplicate]

Solution 1:

Use tee -a (or tee --append) with sudo

tee - read from standard input and write to standard output and files
[...]
   -a, --append
      append to the given FILEs, do not overwrite
[...]

So your command becomes

echo "something" | sudo tee -a /etc/config_file

The advantages of tee over executing Bash with administrative permissions are

  • You do not execute Bash with administrative permissions
  • Only the 'write to file' part runs with advanced permissions
  • Quoting of a complex command is much easier

Solution 2:

The redirection is executed in the current shell. In order to do the redirection with elevated privileges, you must run the shell itself with elevated privileges:

sudo bash -c "somecommand >> somefile"

Solution 3:

Have sudo spawn a sub-shell:

sudo sh -c "echo 'JAVA_HOME=/usr/lib/jvm/java-6-sun' >> /etc/profile"

In this example, sudo runs "sh" with the rest as arguments.

(this is shown as an example in the sudo man page)

Solution 4:

I usually use shell HERE document with sudo tee -a. Something along the lines of:

sudo tee -a /etc/profile.d/java.sh << 'EOF'
# configures JAVA
JAVA_HOME=/usr/lib/jvm/java-8-oracle
export JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
EOF

Solution 5:

In my opinion, the best in this case is dd:

sudo dd of=/etc/profile <<< END
JAVA_HOME=/usr/lib/jvm/java-6-sun
END