0

I want to add a line to a file maintaining the exact pattern

Line i want to add:

export PATH=$PATH:$JAVA_HOME/bin

I dont want to add the values of the variables to the file

What I did:

echo "export PATH=$PATH:$JAVA_PATH/bin" | sudo tee -a /home/admin/Vishal/test.sh

My Output:

Contains numerous paths instead of export PATH=$PATH:$JAVA_HOME/bin

HackersInside
  • 307
  • 2
  • 6
  • 17
  • 2
    You need to escape the dollar signs like this `echo "export PATH=\$PATH:\$JAVA_PATH/bin"` or use single quotes like this `echo 'export PATH=$PATH:$JAVA_PATH/bin'` – accdias Jan 03 '20 at 10:36
  • You absolutely must not use `sudo` to write to a file which belongs to yourself. If the file already exists, you'll be fine, but if the file is created by `root`, you will never be able to edit it yourself. – tripleee Jan 03 '20 at 11:40
  • You really don't want to add that line. You will end up with shells in which PATH has redundant entries (eg `/usr/bin:/bin:/opt/java/latest/bin:/opt/java/latest/bin:/opt/java/latest/bin`). Always use some form of pathmunge: do not blindly append without checking if the desired values are already in the path. – William Pursell Jan 03 '20 at 11:40
  • Looking at [your other question](https://stackoverflow.com/questions/59576295/delete-a-line-containing-exact-pattern-in-linux) I will repeat my comment there: What you are doing seems like a horrible idea. Make the script update the path dynamically instead. Don't seesaw-edit the script itself. – tripleee Jan 03 '20 at 11:41
  • @WilliamPursell i have that in mind but have no idea how to check if the path entry already exist in $PATH – HackersInside Jan 03 '20 at 11:44

1 Answers1

0

The immediate problem is that you need single quotes instead of double. But really, you should not be editing your script file. Instead, make it accept a parameter which tells it whether or not to update the PATH.

case $1 in --update-path) PATH=$PATH:$JAVA_HOME/bin;; esac

If you run /home/admin/Vishal/test.sh --update-path it will add the Java directory; without the option, it won't.

tripleee
  • 175,061
  • 34
  • 275
  • 318