views:

528

answers:

4

What is the proper indentation for a bash script? As a java/c++ monkey I religiously indent my code. But it seems you are not allowed to indent this code:

#! /bin/bash

if [ $# = 0 ]
then
        # there was no arguments => just do to standard output.
        echo "there are no parameters"
else
cat << EOF
==========================================================
==========================================================
==========================================================
==========================================================
DESCRIPTION:

$1
----------------------------------------------------------

EOF
fi

When indented it does not recognize the EOF and if you just unindented the EOF (confusing) it prints indented.

Q: What is the proper indenting for bash scripts?

+2  A: 

This is not a bash indenting problem, this is a here-file problem. The label that you specify after <<, i.e., EOF, must appear alone in a line, without leading or trailing whitespaces.

For the here-file itself, it is used as typed, indentation included.

mouviciel
A: 

Mouviciel is correct.

You can put the here-file text in a separate file if you want to preserve indentation. You would then have to handle the substitution yourself, however.

Steve Emmerson
+8  A: 

With bash (3.2 at least) and ksh (do not know about others) you can indent the here-documents using <<-, and the leading tabs will be stripped (not spaces, only tabs), e.g.

if [...]; then
    cat <<-EOF
        some text
    EOF
fi
Dan Andreatta
Another things that's useful to know is that quoting the beginning delimiter prevents expansion (parameter, command substitution, etc.) of the here-document: `foo << "EOF"` and they can be combined: `foo <<- "EOF"`. The latter is useful for commenting out blocks of code (you can use the no-op `:` as the receiving command or omit it). Also, when using `<<-` you have a choice of whether you want to indent the closing delimiter (or any line, really).
Dennis Williamson
+2  A: 

yes you can "indent", by using <<- (see bash man page on here documents)

if [ $# = 0 ]
then
        # there was no arguments => just do to standard output.
        echo "there are no parameters"
else
    cat <<-EOF
    ==========================================================
    ==========================================================
    ==========================================================
    ==========================================================
    DESCRIPTION:

    $1
    ----------------------------------------------------------
    EOF
fi
ghostdog74
+1. I didn't know that feature!
mouviciel