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

后端 未结 1 1661
-上瘾入骨i
-上瘾入骨i 2020-11-28 15:52

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 m

相关标签:
1条回答
  • 2020-11-28 16:43

    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"
    0 讨论(0)
提交回复
热议问题