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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try replacing
~with$HOME. Tilde expansion only happens when the tilde is unquoted. Seeinfo "(bash) Tilde Expansion".You could also do
file=~/Desktopwithout 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 variablefile=~/"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. Socommand --option=~/foowill only work ifcommanddoes tilde expansion itself, which will vary by command, whilecommand --option="$HOME/foo"will always work.