Re: Q re: if test of command in bash script
On Tue, Oct 28, 2008 at 11:42:09AM -0500, Kent West wrote:
> ===
>
> echo "Does target directory '$targetDir' exist?"
> if [ -d $targetDir ]
> then
> echo "YES, '$targetDir exists!"
> echo
> else
> echo "No, '$targetDir' does not exist."
> echo
> echo "Attempting to create $targetDir"
> echo
> if [ mkdir -p $targetDir ] # If the mkdir fails
> then
> echo "Failed to create directory. Aborting."
> exit 1
> else
> echo "Created $targetDir directory successfully!"
> fi
> fi
>
> ===
>
> When I run this, I get this output:
>
> ===
>
> Does target directory '/TERASTATIONBACKUP/GOSHEN/2008/OCTOBER' exist?
> No, '/TERASTATIONBACKUP/GOSHEN/2008/OCTOBER' does not exist.
>
> Attempting to create /TERASTATIONBACKUP/GOSHEN/2008/OCTOBER
>
> /usr/local/bin/BackupGoshenHome: line 57: [: -p: binary operator expected
> Created /TERASTATIONBACKUP/GOSHEN/2008/OCTOBER directory successfully!
> Tarring up source into target
> /TERASTATIONBACKUP/GOSHEN/2008/OCTOBER/2008-Oct-28.tgz
>
> ===
The complaint about line 57 is from the [ operator, which is expecting a
conditional expression and not a command. Since [ ... ] returns a false
value, the else is executed, whic incorrectly says that mkdir worked.
The [ ... ] construct isn't needed for a command like mkdir, just
for conditional tests of variables and strings (see CONDITIONAL
EXPRESSIONS in bash(1)).
I'd tend to format the above code a little differently, but here's
the same thing with the `if' using the mkdir command directly:
if [ -d $targetDir ]; then
echo -e "YES, '$targetDir exists!\n\n"
else
echo -e "No, '$targetDir' does not exist.\n\n"
echo -e "Attempting to create $targetDir\n\n"
if mkdir -p $targetDir; then
echo "Created $targetDir directory successfully!"
else
echo "Failed to create directory. Aborting."
exit 1
fi
fi
> I've tried various permutations of the test case - put it in
> double-quotes, in single-quotes, put a bang in front of the text, remove
> the brackets, add a semi-colon at the end of the test line before the
> comment, etc, but can't figure out what I'm doing wrong.
>
> Thanks for any help!
>
> --
> Kent West <*)))><
> http://kentwest.blogspot.com
I sympathise with finding understandable documentation or man pages for
these things. Regarding return codes, they're often implicit and not
documented; often the term `exit status' and others might be used. Shell
commands always return an exit status if 0 -- meaning true -- if the command
doesn't fail, and usually 1 otherwise, but some other exit values are used.
See also EXIT STATUS in bash(1).
Ken
--
Ken Irving, fnkci@uaf.edu, 907-474-6152
Water and Environmental Research Center
Institute of Northern Engineering
University of Alaska, Fairbanks
Reply to: