Bash 脚本的正确缩进

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28832899/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:27:53  来源:igfitidea点击:

Proper indentation of Bash script

linuxbashubuntu-12.04indentation

提问by paul

I have written a Bash script which uses cases and functions for university, but no matter where I move the scripts, she says that they are not indented properly. What is the correct indentation of this sample of the script?

我写了一个 Bash 脚本,它在大学使用案例和函数,但无论我把脚本移到哪里,她都说它们没有正确缩进。这个脚本示例的正确缩进是什么?

clear
      echo "Start A Process"
echo "*************************"
echo "1. Oxygen Level."
echo "***************************"
echo "2. Temperature ."
echo "*************************"
echo "3. Mars Rover Speed."
echo "*************************"
echo "4. Satellite Distance"
echo "*************************"
echo "5. Carbon Dioxide Level"
echo "*************************"
echo "6. Humidity %."
echo "*************************"
echo "Press A to quit."
echo "*************************"
    read -p "Please make a choice:" choice2

#Choices
case "$choice2" in

1)
$script/simulate start oxygen
echo "Oxygen Level Started."
sleep 5
;;
2)

Is there a website or a function on VMware where I can get my code automatically indented?

VMware 上是否有网站或功能可以让我的代码自动缩进?

回答by David W.

Indenting is done to clarifyyour code. Indentations are usually used for loops, if statements, function definitions to make it easy to see what statements are part of that loop or part of the if statement.

缩进是为了澄清你的代码。缩进通常用于循环、if 语句、函数定义,以便于查看哪些语句是该循环的一部分或 if 语句的一部分。

Another trick to make your code more readable is adding blank lines to separate out blocks of related code. For example, separating out your menufrom the rest of your code with a couple of blank lines:

使您的代码更具可读性的另一个技巧是添加空行以分隔出相关代码块。例如,使用几个空行将菜单与代码的其余部分分开:

clear
echo "Start A Process"

echo "*************************"
echo "1. Oxygen Level."
echo "***************************"
echo "2. Temperature ."
echo ....   #And on and on...
echo "*************************"
echo "6. Humidity %."
echo "*************************"
echo "Press A to quit."
echo "*************************"

read -p "Please make a choice:" choice2

case "$choice2" in...
...

This makes it easier to see the menu you're presenting. You could also use a Here documentto eliminate the repeating echoes and quotation marks that make your menu hard to see. I'd would eliminate the over fancy stuff like the lines of asterisks. They don't add anything to the program and just make it harder to read - both code wise and execution wise:

这样可以更轻松地查看您呈现的菜单。您还可以使用Here 文档来消除使您的菜单难以看到的重复回声和引号。我会消除像星号线这样过于花哨的东西。他们不会向程序添加任何内容,只会让程序更难阅读——无论是代码明智还是执行明智:

clear

cat <<MENU
START A PROCESS
------------------
1. Oxygen Level.
2. Temperature .
3. Mars Rover Speed.
4. Satellite Distance
5. Carbon Dioxide Level
6. Humidity %.
A. Quit
------------------
MENU

read -p "Please make a choice:" choice2

case "$choice2" in...
...

Notice how using a here documentmakes your menu is easy to see and format.

请注意使用此处的文档如何使您的菜单易于查看和格式化。

Finally, your casestatement should follow the indentation rule of keeping common lines indented, so you not only know the code that goes with the casestatement, but that you also indent each choice:

最后,你的case语句应该遵循保持公共行缩进的缩进规则,这样你不仅知道case语句附带的代码,而且还缩进每个选项:

case "$choice2" in
    1)
        $script/simulate start oxygen
        echo "Oxygen Level Started."
        sleep 5
        ;;
    2)
       .....
       .....
       ;;
   .....
esac

Some people will compact this a bit:

有些人会稍微压缩一下:

case "$choice2" in
    1)  $script/simulate start oxygen
        echo "Oxygen Level Started."
        sleep 5;;
    2)  .....
        .....;;
   .....
esac

The indentation is pretty much the same. A few lines are combined to make the casemore compact and easier to read.

缩进几乎相同。几行组合在一起,使内容case更紧凑,更易于阅读。

To help you with indentation and coding, use a program editor instead of just a text editor. A good program editor like VIM will automatically indent your code and even highlight the syntax making it easier to read. Eclipse is used for Java programming, but can be used as a text editor for shell scripts. A good editor can also help you with the way to use certain commands of statements by showing you the manpage for that command. When you press capital Kin VIM, it will show you the manpage for that command.

为了帮助您进行缩进和编码,请使用程序编辑器而不仅仅是文本编辑器。像 VIM 这样好的程序编辑器会自动缩进您的代码,甚至突出显示语法,使其更易于阅读。Eclipse 用于 Java 编程,但也可用作 shell 脚本的文本编辑器。一个好的编辑器还可以通过向您显示该命令的联机帮助页来帮助您了解如何使用某些语句命令。当您K在 VIM 中按大写时,它会显示该命令的联机帮助页。

Bash program beautificationis quite tricky. However, there is a Python programthat will attempt the task.

Bash 程序美化相当棘手。但是,有一个Python 程序将尝试执行该任务。

回答by Walter A

Style will always be a discussion. A good starting point is Google's style guidewhich also provides an overview of a lot of shell-constructions.

风格将永远是一个讨论。一个很好的起点是Google 的样式指南,它也提供了许多 shell 结构的概述。

I happen to disagree with Googles style "Indent 2 spaces. No tabs.", I prefer tabs. Some developers like to see 2 spaces, some 4, and you can change it the way you like (vi: set tabstop=3 indent=3).

我碰巧不同意 Google 的风格“缩进 2 个空格。没有制表符。”,我更喜欢制表符。有些开发者喜欢看 2 个空格,有些是 4 个,你可以按你喜欢的方式改变它(vi:set tabstop=3 indent=3)。

How to show a menu ? You could use ONE echo like this:

如何显示菜单?您可以像这样使用 ONE echo:

   echo "Start A Process
       1. Oxygen Level.
       2. Temperature .
       3. Mars Rover Speed.
       4. Satellite Distance
       5. Carbon Dioxide Level
       6. Humidity %.

       Press A to quit."

When you have more menu's, I would consider using textfiles with the menu lines and catthe correct menu file. You can see an example at https://unix.stackexchange.com/questions/38200/ksh-styling-text-based-menu-using-stderr/115371#115371

当您有更多菜单时,我会考虑使用带有菜单行和cat正确菜单文件的文本文件。你可以在https://unix.stackexchange.com/questions/38200/ksh-styling-text-based-menu-using-stderr/115371#115371看到一个例子

回答by William Pursell

The correct indentation depends on the style desired, which is purely a matter of opinion. In other words, the only person who can answer your question is the mysterious woman you refer to as "she". Personally, I would say you have much bigger problems than indentation. Rather than reading the selection from stdin, you ought to take it as a command line argument. Rather than always printing a menu showing the options, you should only print them in response to -h or --help or something similar. Rather than using a string of consecutive echos, use a single heredoc to print the menu. For example:

正确的缩进取决于所需的样式,这纯粹是见仁见智。也就是说,唯一能回答你问题的人,就是你所谓的“她”这个神秘女人。就个人而言,我会说你有比缩进更大的问题。您应该将其作为命令行参数,而不是从 stdin 中读取选择。不要总是打印显示选项的菜单,您应该只打印它们以响应 -h 或 --help 或类似的东西。不要使用一串连续的回声,而是使用单个 heredoc 来打印菜单。例如:

usage() {  cat <<- EOF
    $(basename 
function echofoo() {
  echo foo
}
) option Start A Process, where option is one of: 1) oxygen level ... 6) Humidity %. EOF }

回答by Michael Jaros

This question has been treated on Unix Stack Exchangealready.

这个问题已经在Unix Stack Exchange上得到了处理。

There is no such thing as a standard for Bash. Usually you indent at least each level of:

Bash 没有标准。通常你至少缩进每个级别:

  • functions
  • loops (for, while)
  • conditionals (if, case)
  • 职能
  • 循环 ( for, while)
  • 条件 ( if, case)

Some examples:

一些例子:

if true
then
  echo foo
else
  echo bar
fi

or

或者

case "$choice" in
  1)
    echo foo
  ;;
  2)
    echo bar
  ;;
    [...]

or

或者

#!/usr/bin/emacs --script

(setq require-final-newline 'visit)

(defun indent-files (files)
  (cond (files
         (find-file (car files))
         (untabify (point-min) (point-max))
         (indent-region (point-min) (point-max))
         (save-buffer)
         (kill-buffer)
         (indent-files (cdr files)))))

(indent-files command-line-args-left)

;; EOF ;;

回答by Shailendra Saxena

Just open the file with vim editor and typing gg=G will reindent the entire file.

只需使用 vim 编辑器打开文件并输入 gg=G 将重新缩进整个文件。

回答by hasanghaforian

I found this answer here:

我在这里找到了这个答案:

Emacs can do that:

Emacs 可以做到:

  • load the file into Emacs
  • press Ctrl-spaceat the top of the file
  • move the cursor to the bottom of the file
  • press Alt-xand type untabifythen return
  • press Alt-xand type indent-regionthen return
  • 将文件加载到 Emacs
  • Ctrl-space文件顶部
  • 将光标移动到文件底部
  • 按下Alt-x并输入untabify然后返回
  • 按下Alt-x并输入indent-region然后返回

This will get rid of tabs and indent everything properly.

这将摆脱制表符并正确缩进所有内容。

If you need to do this more often and do not use Emacs as your editor, you might want to pack it all into a script:

如果您需要更频繁地执行此操作并且不使用 Emacs 作为您的编辑器,您可能希望将其全部打包到一个脚本中:

shfmt -l -w script.sh

回答by Daniel Martí

A bit late to the party, but it looks like shfmtcould do the trick for you. It formats shell/bash code, which includes indentation.

聚会有点晚了,但看起来shfmt可以为您解决问题。它格式化 shell/bash 代码,其中包括缩进。

clear
# Really, really recommend turning this into a here document
echo "Start A Process"
echo "*************************"
echo "1. Oxygen Level."
echo "***************************"
echo "2. Temperature ."
echo "*************************"
echo "3. Mars Rover Speed."
echo "*************************"
echo "4. Satellite Distance"
echo "*************************"
echo "5. Carbon Dioxide Level"
echo "*************************"
echo "6. Humidity %."
echo "*************************"
echo "Press A to quit."
echo "*************************"
read -p "Please make a choice:" choice2

#Choices
case "$choice2" in
 1)
    $script/simulate start oxygen
    echo "Oxygen Level Started."
    sleep 5
    ;;
 2)

回答by Josh Habdas

What is the correct indentation of this sample of the script?

这个脚本示例的正确缩进是什么?

There is none. Indentation is a matter of personal preference. If shesuggests yourcode is not indented correctly you either missed a requirement or the instructions should be updated to state use of proper indentation is required.

空无一人。缩进是个人喜好的问题。如果建议你的代码没有正确缩进,你要么错过了一个要求,要么应该更新说明以说明需要使用正确的缩进。

Is there a website or a function on VMware where I can get my code automatically indented?

VMware 上是否有网站或功能可以让我的代码自动缩进?

No need to automate indentation. Just press the spaceor tabkeys to indent the code you copied.

无需自动缩进。只需按spacetab键即可缩进您复制的代码。

回答by tripleee

While there are no specific standards for shell script, universal indentation conventions dictate that commands on the same level of control should receive the same indentation, and commands which depend on the outcome from the control construct on the previous line should be indented relative to that control construct. Where the control construct ends, the indentation should revert to that of the flow control construct.

虽然 shell 脚本没有特定的标准,但通用缩进约定规定在同一控制级别上的命令应该接受相同的缩进,并且依赖于前一行控制结构的结果的命令应该相对于该控制进行缩进构造。在控制结构结束的地方,缩进应该恢复到流控制结构的缩进。

So in your particular example, the indented echoand readstatements are indented for no good reason relative to the commands which surround them, and the body of the casestatement should be indented.

因此,在您的特定示例中,相对于围绕它们的命令而言,缩进echoread语句没有充分的理由缩进,并且语句的主体case应该缩进。

Most decent editors will do this more or less automatically for you if properly configured.

如果正确配置,大多数体面的编辑器或多或少会自动为您执行此操作。

##代码##

The specifics of the indentation inside the casestatement are less rigid. Some people indent the individual case labels back out to the same level as the governing case, others indent them a full level (here, four spaces). I tend to choose a middle ground so that the body of a case is precisely four spaces indented relative to the governing casestatement.

case语句中缩进的细节没有那么严格。有些人将单个案例标签缩进到与管理相同的级别case,其他人将它们缩进一个完整的级别(这里是四个空格)。我倾向于选择一个中间立场,以便案例的主体相对于管理case声明正好缩进四个空格。