bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Bash style of if-then-else?


From: Eric Blake
Subject: Re: Bash style of if-then-else?
Date: Mon, 23 Aug 2010 15:40:26 -0600
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100806 Fedora/3.1.2-1.fc13 Mnenhy/0.8.3 Thunderbird/3.1.2

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

There is nothing wrong with the other style; however, in the style where 'then' is on a separate line, the newline alone serves as a line terminator and you don't need the ';', as in:

if [ -f "$file" ]
then
  do something
fi

[On a related note, if you are talking in the context of autoconf-related scripts, the preference is to use 'test -f "$file"' rather than '[ -f "$file" ]', so as not to mix up [] with autoconf's use of m4 quotation characters.]

--
Eric Blake   address@hidden    +1-801-349-2682
Libvirt virtualization library http://libvirt.org



reply via email to

[Prev in Thread] Current Thread [Next in Thread]