[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Bash style of if-then-else?
From: |
Ken Irving |
Subject: |
Re: Bash style of if-then-else? |
Date: |
Thu, 23 Sep 2010 15:35:08 -0800 |
User-agent: |
Mutt/1.5.20 (2009-06-14) |
On Thu, Sep 23, 2010 at 04:38:42PM -0500, Michael Witten wrote:
> On Mon, Aug 23, 2010 at 16:40, Eric Blake <eblake@redhat.com> wrote:
> > On 08/23/2010 03:29 PM, Peng Yu wrote:
> >>
> >> Hi,
> >>
> >> I'm wondering if there is a widely accepted coding style of bash scripts.
> >>
> >> lug.fh-swf.de/vim/vim-bash/StyleGuideShell.en.pdf
> >>
> >> I've seen the following style. Which is one is more widely accepted?
> >>
> >> if [ -f $file]; then
> >> do something
> >> fi
> >>
> >> if [ -f $file];
> >> then
> >> do something
> >> fi
> >
> > Neither. You're missing adequate quoting in case $file contains spaces.
> > More importantly, when using '[', the trailing ']' has to be its own
> > argument. Personally, I tend to use the style with fewer lines:
> >
> > if [ -f "$file" ]; then
> > do something
> > fi
>
> This is also possible:
>
> [ -f "$file" ] && do_something
>
> or perhaps:
>
> [ -f "$file" ] && {
> do_something_0
> do_something_1
> }
While we're talking about style... I prefer using 'test' rather than
'[..]' as it seems to me to be more readable.
test -f "$file" && do_something
test -f "$file" && {
do_something_0
do_something_1
}
if test -f $file; then
do something
else
do something else
fi
Are there actual advantages for [] over test? I guess the former uses
one less byte than the latter.
Ken