35

I've written this script:

#!/bin/bash

file="~/Desktop/test.txt"
echo "TESTING" > $file

The script doesn't work; it gives me this error:

./tester.sh: line 4: ~/Desktop/test.txt: No such file or directory

What am I doing wrong?

ruakh
  • 156,364
  • 23
  • 244
  • 282
Mason
  • 6,345
  • 15
  • 67
  • 113
  • Possible duplicate of [Tilde expansion not working in Bash](https://stackoverflow.com/questions/5748216/tilde-expansion-not-working-in-bash) – codeforester Jun 12 '17 at 23:50

2 Answers2

59

Try replacing ~ with $HOME. Tilde expansion only happens when the tilde is unquoted. See info "(bash) Tilde Expansion".

You could also do file=~/Desktop without quoting it, but if you ever replace part of this with something with a field separator in it, then it will break. Quoting the values of variables is probably a good thing to get into the habit of anyway. Quoting variable file=~/"Desktop" will also work but I think that is rather ugly.

Another reason to prefer $HOME, when possible: tilde expansion only happens at the beginnings of words. So command --option=~/foo will only work if command does tilde expansion itself, which will vary by command, while command --option="$HOME/foo" will always work.

Michael Hoffman
  • 27,420
  • 6
  • 55
  • 80
  • 4
    @Mason - also, the tilde expansion happens _before_ the variable expansion, so when `$file` is converted to `~/Desktop/test.txt` you've already missed the tilde expansion phase. See http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions for the order of expansion. – Stephen P Dec 07 '11 at 00:59
1

FYI, you can also use eval:

eval "echo "TESTING" > $file"

The eval takes the command as an argument and it causes the shell to do the Tilde expansion.

Sanghyun Lee
  • 17,726
  • 18
  • 88
  • 118