I want to append several lines of shell commands to a file owned by root. I have sudo
access. In short I want to put this:
export M2_HOME=/opt/apache-maven-3.1.1
export M2=$M2_HOME/bin
PATH=$M2:$PATH
I tried this:
m2config=$(cat << EOL
export M2_HOME=/opt/apache-maven-3.1.1
export M2=\$M2_HOME/bin
PATH=\$M2:\$PATH
EOL
)
and then
sudo bash -c "echo $m2config >> /etc/profile.d/maven.sh"
But to no avail. Does anyone know how to do this? I have consulted many similar questions but none addressing this exact need.
Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.
To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.
To split long commands into readable commands that span multiple lines, we need to use the backslash character (\). The backslash character instructs bash to read the commands that follow line by line until it encounters an EOL.
sudo bash -c "cat >> /etc/profile.d/maven.sh" << EOL
export M2_HOME=/opt/apache-maven-3.1.1
export M2=\$M2_HOME/bin
PATH=\$M2:\$PATH
EOL
If you don't fancy spawning a subshell, sudo tee -a /etc/profile.d/maven.sh > /dev/null << EOL
works just as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With