Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$HOME vs ~ for use in bash scripts

Tags:

bash

$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

like image 911
zen Avatar asked Oct 24 '16 16:10

zen


Video Answer


2 Answers

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.

like image 179
cdarke Avatar answered Oct 01 '22 03:10

cdarke


~ 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
like image 29
Marc B Avatar answered Oct 01 '22 04:10

Marc B