Tilde (~/) not working on if then statement in Shell script

3.6k views Asked by At

I have the following script

file=${file:-letsdump.sh}    
checkfile="~/mysql_backup/$file"
if [ -e "$checkfile" ]; then
mv ~/mysql_backup/$file ~/mysql_backup/$file-bak-$(date +%d%m%Y_%H%M).bak
else
echo 'file doesnt exist'   
fi

I know my file is there, I am thinking it could be something to do with the ~/ ?

It never finds the file

2

There are 2 answers

1
Charles Duffy On BEST ANSWER

Double quotes (really, any quotes) prevent ~ from being expanded. Use instead:

checkfile=~/mysql_backup/"$file"

...or, even better, use $HOME in all scripts, and consider ~ to be a facility for interactive/human use only.

1
Keith Thompson On

The ~ character is not expanded inside double-quoted strings.

In this context, ~ is equivalent to $HOME, which is expanded in double-quoted strings, so you could write:

checkfile="$HOME/mysql_backup/$file"

When followed by a user name, ~ refers to that user's home directory, which is not tracked by any environment variable; "~fred/" would not expand, but writing something that does expand correctly in that context is more difficult. You can leave it outside the quotes, but that could cause problems if the home directory path includes a space -- which I hope would never actually happen. Correction, thanks to Charles Duffy: String splitting is disabled on assignments, so that wouldn't be an issue.