You should use :
mv -f -- "$HOME_DIR/${dir:?}" "$HOME_SAVE/BACKUP/"
The expansion will fail, the script quit, and an error message will be emitted to stderr if $dir
's value is empty.
You can even specify the message printed like:
mv -f -- "$HOME_DIR/${dir:?\$dir is UNSET or NULL!}" "$HOME_SAVE/BACKUP/"
Alternatively - and less ultimately - you can specify default and/or substitute values for $dir
which will only be applied if it is :-
unset or null or :+
set and not null using a similar form. All of these examples - above and below - are representative of a few of several standard POSIX-specified parameter expansion forms.
In the below example when $dir
is set and not null the first portion evaluates to your source directory, else to nothing at all and the second portion evaluates to its value if any, but if none it evals instead to your target dir. mv
is specified to fail when its first and second args name the same pathname and so nothing is moved at all.
mv -f -- "${dir:+$HOME_DIR/}${dir:-$HOME_SAVE/BACKUP/}" "$HOME_SAVE/BACKUP/" 2>/dev/null
That is probably overkill though as I suppose:
mv -f -- "$HOME_DIR/$dir" ${dir:+"$HOME_SAVE/BACKUP/"} 2>/dev/null
...should do just as well - mv
can't move anything nowhere. Note that in a POSIX-conforming shell the quotes even inside the {}
curlies serve to protect the expansion because in that case it is not $dir
's value expanded but instead ${dir:+word}
word's value expanded. Putting them within the braces serves to eval the expansion to nothing at all - not even a null string - when ${dir}
is unset or null. That probably doesn't matter really - I'm fairly certain a null filename is invalid pretty much everywhere - but it's how I usually do it. This is not safe to do with ${dir:-"word"}
however - in that case you would get either ${dir}
's unquoted expansion or word
's quoted expansion.
You might also optionally invoke the -i
nteractive option to mv
only if $dir
is null like:
mv "-i${dir:+f}" -- "$HOME_DIR/$dir" "$HOME_SAVE/BACKUP/" </dev/tty
...and so you would be sure at least not to accidentally overwrite any files in .../BACKUP without someone first pressing a y (or whatever) at the terminal.