20

I tried to get the Android Studio launcher (studio.sh) to use my manually installed Java (not the system-wide default Java). Since I already declared PATH and JAVA_HOME in my .bashrc file, I simply sourced that file in the shell script:

. /home/foobar/.bashrc

but for some reason, $JAVA_HOME/bin/java was still not recognized as an executable file by the script.

I added some logging and found out that JAVA_HOME was expanded as ~/install/java..., i.e. the tilde operator was not expanded into the home directory.

I did some searching, but couldn't find any reason why it was not expanded. Is tilde a Bash-specific feature (the script uses #!/bin/sh, and Linux Mint uses dash, not bash)? Does tilde not work in some circumstances?

I replaced ~ with $HOME in my .bashrc declaration, and then it worked, so HOME is known at runtime.

jdhao
  • 24,001
  • 18
  • 134
  • 273

1 Answers1

25

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:

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • [This answer](http://stackoverflow.com/a/29310477/258523) might be a better one to point at but I haven't really looked at the one you linked too all that carefully. – Etan Reisner Aug 28 '15 at 18:12
  • @EtanReisner Thanks. There are a few long-standing "expand my stored tilde" questions that might warrant de-duping. That's a good one; I'll edit it in. (I'd rather link to the question than the answer, because the breadth of answers is useful to understand advantages and disadvantages of each.) – Jeff Bowman Aug 28 '15 at 18:16
  • Yeah, I've had a few tabs of that sort open for a while waiting for me to decide how to de-dupe them well. I almost posted a meta question about whether it would be possible to get a moderator to migrate some of the better answers to a new canonically asked question or something. – Etan Reisner Aug 28 '15 at 18:18