在子 shell 中运行脚本时,您应该定义哪个 shell 应该运行该脚本。您编写脚本时使用的 shell 类型可能不是系统上的默认 shell,因此当由错误的 shell 执行时,您输入的命令可能会导致错误。
脚本的第一行确定要启动的 shell。第一行的前两个字符应为 #!,然后是 shell 的路径,该 shell 将解释后面的命令。空行也被视为行,因此不要以空行开始脚本。
为了本课程的目的,所有脚本都将以以下行开始
#!/bin/bash
如前所述,这意味着 Bash 可执行文件可以在以下位置找到/bin.
您应该意识到,您可能不是唯一阅读您代码的人。许多用户和系统管理员运行其他人编写的脚本。如果他们想了解您是如何做到的,注释对于启发读者很有用。
注释也使您自己的生活更轻松。假设您必须阅读大量 man 手册才能使用脚本中使用的某个命令来实现特定结果。如果您需要在几周或几个月后更改脚本,您将不会记得它是如何工作的,除非您注释了您做了什么、如何做的和/或为什么这样做。
以script1.sh示例并将其复制到commented-script1.sh,我们对其进行编辑,以便注释反映脚本的作用。shell 在一行中遇到井号标记后的所有内容都将被忽略,并且仅在打开 shell 脚本文件时可见
#!/bin/bash # This script clears the terminal, displays a greeting and gives information # about currently connected users. The two example variables are set and displayed. clear # clear terminal window echo "The script starts now." echo "Hi, $USER!" # dollar sign is used to get content of variable echo echo "I will now fetch you a list of connected users:" echo w # show who is logged on and echo # what they are doing echo "I'm setting two variables now." COLOUR="black" # set a local shell variable VALUE="9" # set a local shell variable echo "This is a string: $COLOUR" # display content of variable echo "And this is a number: $VALUE" # display content of variable echo echo "I'm giving you back your prompt now." echo |
在一个像样的脚本中,前几行通常是对期望内容的注释。然后,每个大的命令块都将根据需要进行注释,以提高清晰度。例如,Linux init 脚本在您系统的init.d目录中,通常都有很好的注释,因为它们必须对每个运行 Linux 的人都是可读和可编辑的。