Why is a tilde in a path not expanded in a shell script?

Solution 1:

In the bash manual, note that brace expansion during parameter substitution, but not recursively:

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion.

This implies that any tilde (or parameter references or command substitution) stored unexpanded in a bash variable will not automatically resolve. Your JAVA_HOME variable contains a literal tilde, so bash will not expand it automatically.

It is likely that your fix worked because tilde expansion does not apply in quotes:

$ echo "~"
~
$ echo ~
/home/jeffbowman

...but parameter expansion like $HOME does occur in quotes. Replacing it with $HOME expands to your home directory during the assignment of JAVA_HOME.

FOO=~/bar        # stores /home/jeffbowman/bar
FOO="~/bar"      # stores ~/bar
FOO=$HOME/bar    # stores /home/jeffbowman/bar
FOO="$HOME/bar"  # stores /home/jeffbowman/bar

Though the better option is to ensure your assignment is correct, if you want to expand it manually, these SO questions have some good options:

  • "Tilde expansion in quotes"
  • "How to manually expand a special variable (ex: ~ tilde) in bash"