0

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.

Cyrus
  • 69,405
  • 13
  • 65
  • 117
Sinh Nguyen
  • 3,191
  • 3
  • 14
  • 23
  • 2
    The shell (`bash`) expands the tilde according to the "Tilde Expansion" rules in the [man page](https://linux.die.net/man/1/bash). If you quote the string, expansion isn't performed, and the literal string is used. You could escape the spaces directly, eg `wc -l ~/foo\ bar` (or even just the bit containing the space, apparently, eg: `wc -l ~/"foo bar"/baz`) – msbit Apr 16 '21 at 00:47
  • 2
    You can use `$HOME` instead of `~` and include it within double quotes. – Benjamin W. Apr 16 '21 at 01:22
  • 2
    this suits better on [unix.se] where there are already lots of duplicates. [Why doesn't the tilde (~) expand inside double quotes?](https://unix.stackexchange.com/q/151850/44425), [Getting negative on test for HOME directories with tilde ~ expansion](https://stackoverflow.com/q/25418238/995714), [Tilde in path doesn't expand to home directory](https://stackoverflow.com/q/5748216/995714), [How to expand tilde (~) in path (duplicate)](https://stackoverflow.com/q/40128376/995714), [Why isn't tilde (~) expanding inside double quotes? (duplicate)](https://stackoverflow.com/q/41871596/995714), – phuclv Apr 16 '21 at 03:07

1 Answers1

2

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
John Kugelman
  • 307,513
  • 65
  • 473
  • 519