shellfilehome-directorytilde-expansion

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


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


Solution

  • 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.