$HOME vs ~ for use in bash scripts
I want to make my code more consistent. Should I use
export export_location=~/.bash_profile
or
export path_bash="$HOME/root/config/bash/"
Both appear to work fine, but which is best so I can make my code base consistent
Tilde ~
is replaced by the contents of $HOME
, but only when it is unquoted.
Your examples are apples and oranges, what you should compare is:
export path_bash="~/root/config/bash/"
export path_bash="$HOME/root/config/bash/"
Now they are similar and can be compared. The first one will not be expanded. This is an issue if you need other expansion which requires quotes, like another variable or whitespace.
As a general principle code should be easy to read, and $HOME
is more obvious than a ~
, although that is subjective.
~
has no special meaning within a string, it's just a squiggly character:
$ echo ~
/home/marc
$ echo "~"
~
That's where $HOME
comes in, which CAN be used within a string and get expanded out to the user's home directory
$ echo $HOME
/home/marc
$ echo "$HOME"
/home/marc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With