简体   繁体   中英

What is the proper indentation for bash scripts?

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?

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), eg

if [...]; then
    cat <<-EOF
        some text
    EOF
fi

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

This is not a bash indenting problem, this is a here-file problem. The label that you specify after << , ie, 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM