Search code examples
bashshelldifftilde

bash diff fails to found existing files when providing a path variable containing tilde (~)


I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar

So my question is:

Why ? :-)


Solution

  • ~ is a feature of shell expansion.
    Double quotes limit the expansion to only three features:

    1. Command substitution: $(some command here) or `some command here`
    2. Variable substitution: $VAR or ${VAR}
    3. Arithmetic: $((2+2))

    so when put inside double quotes, the ~ is not expanded