Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"~/Desktop/test.txt: No such file or directory"

Tags:

bash

shell

unix

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?

like image 661
Mason Avatar asked Dec 07 '11 00:12

Mason


1 Answers

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.

like image 66
Michael Hoffman Avatar answered Oct 02 '22 15:10

Michael Hoffman