bashtilde-expansion

Bash tilde not expanding in certain arguments, such as --home_dir=~


Bash is not expanding the ~ character in the argument --home_dir=~. For example:

$ echo --home_dir=~
--home_dir=~

Bash does expand ~ when I leave out the hyphens:

$ echo home_dir=~
home_dir=/home/reedwm

Why does Bash have this behavior? This is irritating, as paths with ~ are not expanded when I specify that path as an argument to a command.


Solution

  • bash is somewhat mistakenly treating home_dir=~ as an assignment. As such, the ~ is eligible for expansion:

    Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed.

    Since --home_dir is not a valid identifier, that string is not mistaken for an assignment.

    Arguably, you have uncovered a bug in bash. (I say arguably, because if you use set -k, then home_dir=~ is an assignment, even though it is after, not before, the command name.)


    However, when in doubt, quote a string that is meant to be treated literally whether or not it is subject to any sort of shell processing.

    echo '--home_dir=~'
    

    Update: This is intentional, according to the maintainer, to allow assignment-like argument for commands like make to take advantage of tilde-expansion. (And commands like export, which for some reason I was thinking were special because they are builtins, but tilde expansion would have to occur before the actual command is necessarily known.)