说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix2/shellprog.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
17.15. Shell Programming
shell 脚本常用来把一组应该一起执行的命令组合在一起。shell 脚本(shell script)是一个可执行的文本文件,由一串 shell 命令组成,运行时按顺序执行这些命令。shell 还有循环和条件这样的语言结构,可以用来编写复杂而功能丰富的脚本。这些 shell 编程结构既可以用在命令行上,也可以用在 shell 脚本里。下面我们给出几个 Bash shell 编程的例子。其他 shell(例如 zsh、sh、tcsh)有它们自己的 shell 编程语言语法,但提供的功能都差不多。
Shell scripts are often used to group a set of commands that should execute together. A shell script is an executable text file that consists of a sequence of shell commands that, when run, execute those commands in order. Shells also have language constructs such as loops and conditionals, which can be used to create complex featureful scripts. These shell programming constructs can also be used at the command line and in shell scripts. Below, we present a few examples of Bash shell programming. Other shells (e.g.
zsh,sh,tcsh) have their own shell programming language syntax, but they all provide similar functionality.
Bash 脚本的第一行以一个特殊的注释开头:# 后跟一个感叹号 !(bang),再跟执行该脚本文件内容的程序的路径。下面是一个简单 Bash 脚本的例子,simplescript.sh(注意,按照惯例,shell 脚本的文件名带 .sh 后缀)。
The first line of a Bash script starts with a special comment
#followed by a bang!and the path to the program that executes the contents of the script file. Below is an example of a simple Bash script, simplescript.sh (note that by convention shell scripts are named with a.shsuffix).
1 | #!/bin/bash |
在运行之前,simplescript.sh 文件需要被赋予可执行权限。用户可以运行 ls -l 检查它的权限,如果没有设置可执行权限,就用 chmod 设置。例如:
Before it can be run, the
simplescript.shfile needs to be given the executable permission. A user can check its permissions by runningls -land set the executable permission usingchmodif it is not set. For example:
1 | $ ls -l simplescript.sh |
一旦被标记为可执行,脚本就可以像任何可执行文件一样在命令行上运行,脚本中列出的命令会按顺序执行:
Once it is marked as executable, the script can be run on the command line like any executable file, and the sequence of commands listed in the script will execute in order:
1 | $ ./simplescript.sh |
Unix shell 程序支持迭代(即 for 和 while 循环)和条件(即 if-else)这样的语言结构。虽然这些结构可以在命令行上使用,但它们更常用在 shell 脚本中,用来描述更复杂的执行结构。shell 脚本还可以使用命令行参数和变量,这有助于脚本处理不同的输入值。
Unix shell programs support language constructs such as iteration (i.e., for and while loops) and conditionals (i.e., if-else). Although these constructs can be used at the command line, they are more commonly used in shell scripts to specify more complicated execution structure. Shell scripts can also make use of command line arguments and variables, which help the script work with different input values.
下面是几个使用了这些更高级特性的 Bash shell 脚本例子。第一个是 runsh.sh,它把某个程序的计时运行重复若干次。在这个例子中,可执行文件名和重复运行的次数作为命令行参数传给脚本。这个例子还展示了如何检查命令行参数的某些约束。这里,程序可执行文件这个命令行参数是运行脚本所必需的,而重复运行的次数是一个可选的命令行参数(如果用户运行脚本时没有指定这个命令行选项,脚本就用默认值 5)。脚本用 if-elif 结构检查命令行选项。它还展示了一个 for 循环的例子,用来按调用者指定的次数重复运行。
Below are a couple examples of Bash shell scripts using some of these more advanced features. The first, runsh.sh, is a script that repeats some timed executions of a program. In this example, the executable file name and the number of executions to repeat are given as command line arguments to the script. This example also shows how to test for some constraints on command line arguments. Here the program executable command line argument is required to run the script, but the number of executions to repeat is an optional command line argument (the script uses a default value of 5 when a user runs the script without specifying this command line option). The script uses the
if-elifconstruct to test for command line options. It also shows an example of aforloop used to repeat the number of runs specified by the caller.
译注
链接文字「runsh.sh」与实际文件名不一致,链接指向的、下文一直使用的都是 run.sh。另外,下面的脚本实际用的是两个独立的 if 语句,并没有用到 elif。
1 | #!/bin/bash |
这个脚本中有几点值得注意。第一,Bash 脚本中没有类型,因此要由用户根据值隐含的类型恰当地使用它们。
There are a few things to note in this script. First, there are no types in Bash scripts, so it is up to the user to use values appropriately based on their implied types.
第二,注意 Bash shell 变量用 = 运算符赋值,用 $var_name 引用它们的值:
Second, note that Bash shell variables are set using
=operator and their values are referenced using$var_name:
1 | N=5 # set N to 5 |
第三,注意在 Bash 脚本中访问命令行参数的语法:
Third, note the syntax for accessing command line arguments in the Bash script:
$@是命令行参数的数组,类似于 C 中的argv。
$@is the array of command line arguments, which is similar toargvin C.
译注
与 C 的 argv 不同,$@ 只包含 $1、$2、……,不包含脚本名;脚本名在 $0 中。译者在 Mac 上用 bash argt.sh x y 验证:$@ 展开为 x y,$# 为 2,$0 是脚本路径。这与下一条所说 $# 不计脚本名是一致的。
$#是命令行参数的个数,类似于 C 中的argc,区别是 Bash 脚本文件名不算作参数之一(即不带命令行参数运行的 Bash 脚本,$#的值为0;而不带命令行参数运行的 C 程序,argc的值为 1)。
$#is the number of command line arguments, which is similar toargcin C except that the name of the Bash script file does not count as one of the arguments (i.e., a Bash script run with no command line arguments has a value of0for$#, whereas a C program run with no command line arguments has a value of 1 forargc).
第四,注意 if-else 的语法及其一般形式:
Fourth, note the
if-elsesyntax, and its general form:
1 | if [[ cond ]] |
Bash 用 then、else 和 fi 分别表示 if 块的开始、else 块的开始和 if-else 语句的结束。[[ 和 ]] 符号用来括起条件语句,它们与条件之间的空格非常重要(没有这些空格,Bash 就无法正确解析这条语句)。条件运算符的语法是:-gt 表示大于,-lt 表示小于,-eq 表示等于,其他运算符也使用类似的记法。
Bash uses
then,else, andfito denote the start of the if block, the start of the else block, and the end of the if-else statement. The[[and]]symbols are used to denote the conditional statement, and the space chars between them and the condition are very important (without these Bash will not correctly parse this statement). The conditional operator syntax is-gtrepresents greater than,-ltrepresents less than,-eqrepresents equal to, and others use similar notation.
最后,注意 for 循环的语法与 C 中的 for 循环类似:for 循环体用 do 和 done 标出,init; cond; step 三部分写在双括号内。下面是这类 Bash for 循环的一般形式(Bash 实际上有不止一种形式的 for 循环):
Finally, note the syntax of the
forloop is similar toforloops in C, where the body of the for loop is denoted bydoanddoneand contains theinit; cond; stepparts inside double parentheses. Here is the general form of this type of Bashforloop (Bash actually has more than one form offorloop):
1 | for ((init; cond; step)) |
下面是 run.sh 脚本的几次运行示例:
Below are some sample runs of the
run.shscript:
1 | $ ./run.sh |
使用 run.sh 这类产生大量输出的脚本时,把输出保存到一个文件中,等运行结束后再查看,常常很有帮助。一种做法是用 I/O 重定向把脚本的输出重定向到文件。下面是用命令行选项 ./myprog 和 10 运行 run.sh 脚本的例子,它把脚本的 stderr 和 stdout 输出重定向到一个名为 results 的文件:
Often when using scripts like
run.shthat produce a lot of output, it is helpful to save the output to a file that can be examined after completion. One way to do this is to use I/O redirection to redirect the script’s output to a file. Below is an example run of therun.shscript with the command line options./myprogand10that redirects its stderr and stdout ouput to a file namedresults:
1 | $ ./run.sh ./myprog 10 &> results |
除了支持类似 C for 循环的语法之外,Bash 还支持遍历一组元素的 for 循环语法。下面列出的 Bash 脚本 forloops.sh 中有几个这类 for 循环的例子,展示了获得被遍历元素集合的不同方式。
In addition to supporting syntax similar to a C
forloop, Bash supportsforloop syntax for iterating over a set of elements. The forloops.sh Bash script (listed below), has a few examples of this type offorloop, showing different ways in which the set of elements iterated over is obtained.
1 | #!/bin/bash |
运行时,输出为:
When run, the output is:
1 | $ ./forloops.sh |
一般来说,把 Unix 命令与循环、条件、命令行、变量等 Bash shell 语言结构结合起来,用户就能编写出强大的 shell 脚本来完成复杂的操作。本节只展示了几个例子。更多信息请参阅 Bash shell 编程指南。
In general, combining Unix commands with Bash shell language constructs like loops, conditionals, command lines, and variables, allow a user to write powerful shell scripts to perform complex actions. We have shown just a few examples in this section. See a Bash shell programming guide for more information.
17.15.1. 参考资料
17.15.1. References
更多信息参见:
For more information see:
- gnu.org 上的 Bash 参考手册。
- Bash Reference Manual from gnu.org.
- Machtelt Garrels 著 Bash Guide for Beginners(Bash 初学者指南)
- Bash Guide for Beginners by Machtelt Garrels
- Mendel Cooper 著 Advanced Bash-Scripting Guide(高级 Bash 脚本编程指南)
- Advanced Bash-Scripting Guide by Mendel Cooper
- cheat-sheets.org 上的最常用的 Unix 命令
- most used Unix commands from cheat-sheets.org