stat is only useful to get information that you can't get from basic shell commands, such as a file's modification time or permissions. To just test the existence of a file, use the
test command, also spelled
[. This command is built into most shells.
if [ -e last_dump.sql ]; then mysql -D my_database < last_dump.sql; fi
-e tests whether the specified file exists; the file can be of any type, including broken symbolic links. If you only want regular files (including symlinks to regular files), use
[ … ] is preferable to
stat for many reasons:
stat just to discard its output is an obfuscated way of testing whether a file exists. Think of the people who will read the code (such as you in six months):
[ -e file ] plainly says “does
file exist?”, whereas calling
stat says “give me the file's metadata” and testing for existence is merely a side effect.
[ … ] is a standard command, whereas
stat doesn't exist on all Unix variants and has incompatible command line options where it exists. In this specific case it isn't so bad because.you aren't using any command line options.
stat is slower since it's an external command.
You should also refrain from using
&& when you mean “if”. This too is markedly less readable. It's also less robust since under
set -e (telling the shell to exit if any program breaks),
[ -e last_dump.sql ] && mysql … aborts the script if
last_dump.sql doesn't exist, whereas
if [ -e last_dump.sql ]; then …; fi keeps going.