bashquotesdouble-quotesspacestilde-expansion

How to use `~` inside a double quote path reference


This command will cause an error

wc -l "~/tmp.txt"
wc: '~/tmp.txt': No such file or directory

While these command running fine

wc -l ~/tmp.txt
14 /home/user/tmp.txt

wc -l "/home/user/tmp.txt"
14 /home/user/tmp.txt

What is the difference? Can I do something to still include the "~" inside a double quote in case there are blank space in the path.


Solution

  • A tilde is only expanded if it's unquoted. Quoting (or, equivalent, prepending a backslash) disables expansion and turns them into literal tildes.

    It's permissible to begin and end quotes mid-argument. You can quote the spaces while leaving the tilde unquoted. These are all equivalent:

    wc -l ~/"file name with spaces.txt"
    wc -l ~/'file name with spaces'.txt
    wc -l ~/file\ name\ with\ spaces.txt