简体   繁体   English

适当缩进Bash脚本

[英]Proper indentation of Bash script

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. 我编写了一个Bash脚本,它使用大学的案例和函数,但无论我在哪里移动脚本,她都说它们没有正确缩进。 What is the correct indentation of this sample of the script? 这个脚本示例的正确缩进是什么?

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上是否有网站或功能,我可以自动缩进代码?

Indenting is done to clarify your 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 menu from 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 document to eliminate the repeating echoes and quotation marks that make your menu hard to see. 您还可以使用Here文档来消除重复的回声和引号,使您的菜单难以看清。 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: 它们不会给程序添加任何东西,只是让它更难阅读 - 代码明智和执行明智:

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 document makes your menu is easy to see and format. 请注意如何使用here文档使您的菜单易于查看和格式化。

Finally, your case statement should follow the indentation rule of keeping common lines indented, so you not only know the code that goes with the case statement, 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 case more 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. 像VIM这样的优秀程序编辑器会自动缩进代码,甚至突出显示语法,使其更易于阅读。 Eclipse is used for Java programming, but can be used as a text editor for shell scripts. Eclipse用于Java编程,但可以用作shell脚本的文本编辑器。 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 K in VIM, it will show you the manpage for that command. 当您在VIM中按下大写K时,它将显示该命令的联机帮助页。

Bash program beautification is quite tricky. Bash程序的美化非常棘手。 However, there is a Python program that will attempt the task. 但是,有一个Python程序将尝试该任务。

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. 您不应该从stdin中读取选择,而应该将其作为命令行参数。 Rather than always printing a menu showing the options, you should only print them in response to -h or --help or something similar. 而不是总是打印显示选项的菜单,您应该只打印它们以响应-h或--help或类似的东西。 Rather than using a string of consecutive echos, use a single heredoc to print the menu. 使用单个heredoc打印菜单,而不是使用一串连续的回声。 For example: 例如:

usage() {  cat <<- EOF
    $(basename $0) option

    Start A Process, where option is one of:
    1) oxygen level
    ...
    6) Humidity %.      
EOF
}

Style will always be a discussion. 风格永远是一个讨论。 A good starting point is Google's style guide which 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. 我碰巧不同意谷歌风格“缩进2个空格。没有标签。”,我更喜欢标签。 Some developers like to see 2 spaces, some 4, and you can change it the way you like (vi: set tabstop=3 indent=3). 一些开发人员喜欢看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 cat the correct menu file. 当你有更多的菜单的,我会考虑使用TEXTFILES与菜单线和cat正确的菜单文件。 You can see an example at https://unix.stackexchange.com/questions/38200/ksh-styling-text-based-menu-using-stderr/115371#115371 您可以在https://unix.stackexchange.com/questions/38200/ksh-styling-text-based-menu-using-stderr/115371#115371上查看示例

This question has been treated on Unix Stack Exchange already. 这个问题已经在Unix Stack Exchange上处理过了。

There is no such thing as a standard for Bash. Bash没有标准。 Usually you indent at least each level of: 通常你至少缩进每个级别:

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

Some examples: 一些例子:

function echofoo() {
  echo foo
}

or 要么

if true
then
  echo foo
else
  echo bar
fi

or 要么

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

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. 虽然没有针对shell脚本的特定标准,但是通用缩进约定规定同一控件级别上的命令应该接收相同的缩进,并且依赖于前一行上的控件构造的结果的命令应该相对于该控件缩进构造。 Where the control construct ends, the indentation should revert to that of the flow control construct. 在控制构造结束的地方,压痕应该恢复到流动控制构造的压痕。

So in your particular example, the indented echo and read statements are indented for no good reason relative to the commands which surround them, and the body of the case statement should be indented. 因此,在您的特定示例中,缩进的echoread语句相对于围绕它们的命令没有任何理由而缩进,并且case语句的主体应缩进。

Most decent editors will do this more or less automatically for you if properly configured. 如果配置正确,大多数体面的编辑器会或多或少地为您自动执行此操作。

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)

The specifics of the indentation inside the case statement are less rigid. case语句中缩进的细节不那么严格。 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). 有些人将个别案例标签缩进到与管理case相同的级别,其他人将它们缩进到完整级别(此处为四个空格)。 I tend to choose a middle ground so that the body of a case is precisely four spaces indented relative to the governing case statement. 我倾向于选择一个中间地面,以便案件的主体恰好是相对于管理case陈述缩进的四个空格。

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

I found this answer here : 我在这里找到了这个答案:

Emacs can do that: Emacs可以这样做:

  • load the file into Emacs 将文件加载到Emacs
  • press Ctrl-space at the top of the file 按文件顶部的Ctrl-space
  • move the cursor to the bottom of the file 将光标移动到文件的底部
  • press Alt-x and type untabify then return Alt-x并键入untabify然后返回
  • press Alt-x and type indent-region then return 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作为编辑器,则可能需要将其全部打包到脚本中:

#!/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 ;;

A bit late to the party, but it looks like shfmt could do the trick for you. 派对有点晚了,但看起来shfmt可以帮你解决问题。 It formats shell/bash code, which includes indentation. 它格式化shell / bash代码,其中包括缩进。

shfmt -l -w script.sh

What is the correct indentation of this sample of the script? 这个脚本示例的正确缩进是什么?

There is none. 空无一人。 Indentation is a matter of personal preference. 缩进是个人偏好的问题。 If she suggests your code 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 space or tab keys to indent the code you copied. 只需按空格键或制表键即可缩进您复制的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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