0

I am trying to write a script which will add the JAVA_HOME path to bashrc. But I keep getting the wrong output.

Using the script below:

echo "export JAVA_HOME=/usr/lib/jvm/java-7-oracle" >> ~/.bashrc
echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc

I get the output below in bashrc

export JAVA_HOME=/usr/lib/jvm/java-7-oracle
export PATH=/home/ubuntu/apache-maven-3.3.9/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr$

The desired output is export PATH=$PATH:$JAVA_HOME/bin for the path.

This script is not just intended for adding java path, I wan't to add path for hadoop, spark and hbase. I get same output for each of those. Any help would be appreciated.

AA Aa
  • 15
  • 3
  • what is the output of the commands if the `>> ~/.bashrc` part is removed? –  Feb 11 '17 at 02:01

3 Answers3

1

What is happening is that $PATH and $JAVA_HOME are being expanded before the line is added to .bashrc.

They need to be escaped; e.g.

echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> ~/.bashrc

or

echo 'export PATH=$PATH:$JAVA_HOME/bin' >> ~/.bashrc

However, you want to be really careful with this kind of "brute-force" editing of shell "rc" files. It can be dangerous.

A better idea would be to either do the changes by hand, or put the settings into the respective wrapper scripts that launch your Java-based applications

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

echo is just outputting the command text, get rid of the echo, and actually execute the command.

slambeth
  • 887
  • 5
  • 17
0

The issue is that you are using double quotes. These evaluate the variables (in this case $JAVA_HOME, which isn't set yet). If you use single quotes instead, it will output the literal instead of the evaluated. e.g.

echo 'export JAVA_HOME=/usr/lib/jvm/java-7-oracle' >> ~/.bashrc echo 'export PATH=$PATH:$JAVA_HOME/bin' >> ~/.bashrc

See Difference between single and double quotes in Bash for more information.

Community
  • 1
  • 1
lewisjb
  • 678
  • 10
  • 26