Re: Q re: if test of command in bash script
On Tue, Oct 28, 2008 at 01:57:40PM -0500, Kent West wrote:
> Ken Irving wrote:
> ...
> > 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"
>
> Ah, the "-e" enables things like newlines and the bell character. No
> wonder my bell character never sounded in another part of my script; I
> just assumed it was something turned off in my terminal settings.
I use it a lot (but I think just needed one \n above), and often without
quoting the whole thing, e.g.,
echo -e \\nleading blank line to separate output from previous lines
> ...
> I at first liked the format
>
> if test
> then
> statement 1
> else
> statement 2
> fi
>
> because I don't have to remember the semi-colon (when it's used; when
> it's not, etc), and because it sort of conceptually separates the test
> from the consequences of the test, but I'm beginning to swing around to
> your format of
>
> if test; then
> statement 1
> else
> statement 2
> fi
>
> Is there any advantage/disadvantage to one format over the other?
No difference, bash just uses the `;' to mean the same thing as a
newline. I just like that the latter form is a bit more concise looking
(to me, anyway).
If there's no else condition to worry about, the && and || operators
can be used to good effect, e.g.,
test -d $targetdir || {
test -n "$OK_TO_CREATE_DIR" || {
echo directory not found
exit 1
}
mkdir -p $targetdir || exit 1 # (mkdir itself emits a complaint)
# ASSERT: mkdir was succesful
}
# ASSERT: directory exists
Ken
--
Ken Irving, fnkci@uaf.edu, 907-474-6152
Water and Environmental Research Center
Institute of Northern Engineering
University of Alaska, Fairbanks
Reply to: