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 ebl...@redhat.com +1-801-349-2682
Libvirt virtualization library http://libvirt.org