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

和自甴很熟 提交于 2019-12-17 07:54:49

问题


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.


回答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"


来源:https://stackoverflow.com/questions/32276909/why-is-a-tilde-in-a-path-not-expanded-in-a-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!