Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Sudo Cat Multiline Commands to Shell Script

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.

like image 304
David Williams Avatar asked Nov 29 '13 21:11

David Williams


People also ask

How do you write a multi line command in a shell script?

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.

How do I put multiple lines in a cat file?

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.

How do you execute multiple lines in bash?

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.


1 Answers

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.

like image 151
pobrelkey Avatar answered Oct 24 '22 17:10

pobrelkey