40

Is there any reason to use the variable $HOME instead of a simple ~ (tilde) in a shell script?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
mybuddymichael
  • 1,660
  • 16
  • 20

3 Answers3

44

Tilde expansion doesn't work in some situations, like in the middle of strings like /foo/bar:~/baz

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Random832
  • 37,415
  • 3
  • 44
  • 63
17

Portability and uniformity of $HOME. Tilde is a typing shortcut.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
evolvah
  • 625
  • 4
  • 15
  • 1
    So I'm correct in understanding that there are shells or systems in which tilde is not synonymous with $HOME? – mybuddymichael May 10 '11 at 02:59
  • 7
    @Michael yes, the default `sh` in Solaris 10 does not treat tilde as `$HOME` neither is does expand `~username`. – evolvah Apr 02 '12 at 03:44
15

Today I found tilde expansion doesn't work in double quotation("").

In zsh(sorry I didn't check the behavior of other shells.),

Inside double quotes (""), parameter and command substitution occur

Tilde expansion is a filename expansion, so it fails inside double quotation.
$HOME is a parameter substitution and can be expanded inside double quotation.
$HOME is a safe bet.

no_allotment
  • 151
  • 1
  • 6