Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
If you intend to use bash, you should use [[, not [. Only use [ if you are scripting for POSIX sh. The Bash FAQ 31 explains the difference from [ and test. [[ is much safer and more powerful. It's also part of bash syntax, whereas [ is a command and not syntax, so bash -n can't tell the difference between [ invalid arg and echo invalid arg. –  jw013 Jul 2 '12 at 15:35
1  
I've incorrectly labeled my question. I'm using sh. Thank you. –  a coder Jul 2 '12 at 15:40
add comment

1 Answer

up vote 9 down vote accepted

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

share|improve this answer
    
Any idea why bash -n gave the script a pass? Shouldn't it have identified the syntax error? –  a coder Jul 2 '12 at 15:15
    
I've never seen the -n option for Bash. It's not in the GNU manual or the BSD manual. –  Shawn J. Goff Jul 2 '12 at 15:18
    
Check this answer: stackoverflow.com/a/4874883/721073 –  a coder Jul 2 '12 at 15:21
2  
The only thing I can think is that [ is not so much part of shell syntax, it's actually a program invocation (even though it's usually a program built in to the shell). I would imagine the -n doesn't give any guarantees about correct command invocation. –  Shawn J. Goff Jul 2 '12 at 15:23
1  
Ah, that -n is part of set; the shell will pass appropriate commandline switches through set. –  Shawn J. Goff Jul 2 '12 at 15:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.