bash 脚本的正确缩进是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2297533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the proper indentation for bash scripts?
提问by sixtyfootersdude
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:
bash 脚本的正确缩进是什么?作为一个 java/c++ 猴子,我虔诚地缩进了我的代码。但您似乎不允许缩进此代码:
#! /bin/bash
if [ $# = 0 ]
then
# there was no arguments => just do to standard output.
echo "there are no parameters"
else
cat << EOF
==========================================================
==========================================================
==========================================================
==========================================================
DESCRIPTION:
----------------------------------------------------------
EOF
fi
When indented it does not recognize the EOF and if you just unindented the EOF (confusing) it prints indented.
缩进时,它无法识别 EOF,如果您只是取消缩进 EOF(令人困惑),它会打印缩进。
Q:What is the proper indenting for bash scripts?
问:bash 脚本的正确缩进是什么?
回答by Dan Andreatta
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.
使用 bash(至少 3.2)和 ksh(不知道其他人),您可以使用缩进此处的文档<<-,并且将去除前导制表符(不是空格,只有制表符),例如
if [...]; then
cat <<-EOF
some text
EOF
fi
回答by ghostdog74
yes you can "indent", by using <<-(see bash man page on here documents)
是的,您可以使用“缩进” <<-(请参阅此处文档中的 bash 手册页)
if [ $# = 0 ]
then
# there was no arguments => just do to standard output.
echo "there are no parameters"
else
cat <<-EOF
==========================================================
==========================================================
==========================================================
==========================================================
DESCRIPTION:
----------------------------------------------------------
EOF
fi
回答by mouviciel
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.
这不是 bash 缩进问题,这是一个 here-file 问题。您在 之后指定的标签<<,即 ,EOF必须单独出现在一行中,不能有前导或尾随空格。
For the here-file itself, it is used as typed, indentation included.
对于 here-file 本身,它用作类型,包括缩进。
回答by Steve Emmerson
Mouviciel is correct.
Mouviciel 是正确的。
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.
如果要保留缩进,可以将此处文件文本放在单独的文件中。但是,您随后必须自己处理替换。

