Issue
I want to write a bash script which creates other bash scripts. But when I do
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/SOME/PATH" >> NEWFILE.sh
it already replaces $LD_LIBRARY_PATH
in the first script.
So in NEWFILE.sh I only get:
export LD_LIBRARY_PATH=:~/SOME/PATH
But i want that in the NEWFILE.sh there's still:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/SOME/PATH
So it gets replaced, when running NEWFILE.sh. I hope this makes sense. Thank you for your help
Solution
If you don't want the variable interpolated, use single quotes:
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/SOME/PATH' >> NEWFILE.sh
But even this small snippet has issues. When NEWFILE.sh
runs with an empty LD_LIBRARY_PATH, it will create an invalid value that has a leading :
. Also, it is bad practice to use ~ in variables. Instead, you should do:
echo 'export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}${LD_LIBRARY_PATH:+:}$HOME/SOME/PATH' >> NEWFILE.sh
Also, this snippet makes NEWFILE.sh not idempotent, and you may wind up with multiple instances of $HOME/SOME/PATH
in the final value. This is easy enough to avoid, but takes a bit more logic. Something like:
cat << \EOF >> NEWFILE.sh
pathmunge () { case ":${LD_LIBRARY_PATH}:" in *:"$1":*) ;;
*) LD_LIBRARY_PATH="$LD_LIBRARY_PATH${LD_LIBRARY_PATH:+:}$1";; esac; }
pathmunge $HOME/SOME/PATH
export LD_LIBRARY_PATH
EOF
This uses a common technique of quoting the HEREDOC (the backslash before the EOF is essential; see how it changes when you remove the leading backslash) to prevent interpolation, and allows multi-line output and quotes to be used in the content that is going to be written to NEWFILE.sh.
One small point is that this will wind up putting the expansion of $HOME in LD_LIBRARY_PATH, which is probably what you want. If you really do want $HOME
in the path (so that it is expanded when LD_LIBRARY_PATH is used, rather than when it is defined), you could do pathmunge '$HOME/path'
, but you may wind up with duplicate instances in the final value, since pathmunge
will not recognize the unexpanded value as matching the expanded value. Avoiding that duplication is an exercise left for the reader.
Note that, depending on the remaining content of NEWFILE.sh, you may want to ensure that pathmunge
is only defined once, and that this definition is not overriding some other definition. pathmunge
is a common name for a function used for modifying PATH so you may want to consider a different name, or adding logic to allow it to take the name of the variable to be overridden.
Answered By - William Pursell Answer Checked By - Terry (WPSolving Volunteer)