BASH: Sudo Cat Multiline Commands to Shell Script
bash, linux, maven, shell
Solution
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.
Problem
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.