Shell backup script, missing `]`

control flowshellshell-script

I'm putting together a simple backup script that will tar contents of a folder, then move that file to a backup server. The script makes sure that the tar file exists and is not zero bytes before moving around.

The problem is that the script is dying on one of the IF lines

if [ -f /www/archives/pdf/pdf_201207021048.tar && 11294720 -gt 0 ]; then
    echo "tar file exists and is greater than 0 bytes."
else
    echo "tar file does not exist or is zero bytes"
fi

The error in the console is:

./backup_pdf.sh: line 49: [: missing `]'

Line 49 is the if statement above.

The script is successfully verified with

sh -n backup.sh

What's wrong that sh is seeing a missing ']', yet it passes the syntax check?

Best Answer

The problem is that && is not a valid operator for [. It needs -a instead, or [ condition ] && [ other_condition ].

&& is a separator (as is ;, ||, & and \n) in a posix shell. It sees the statement [ -f www/archives/pdf/pdf_201207021048.tar; the statement ends becaues there is a &&, then there is another statement (which also would cause an error if it got to it) that looks like 11294720 -gt 0 ], and that statement is terminated with ;.

Related Question