有些脚本完全无需用户交互即可运行。非交互式脚本的优点包括
脚本每次都以可预测的方式运行。
脚本可以在后台运行。
然而,许多脚本需要来自用户的输入,或者在脚本运行时向用户提供输出。交互式脚本的优点包括,但不限于
可以构建更灵活的脚本。
用户可以在脚本运行时自定义脚本或使其以不同的方式运行。
脚本可以在运行时报告其进度。
在编写交互式脚本时,永远不要吝啬注释。打印适当消息的脚本更用户友好,并且更容易调试。脚本可能做得非常完美,但如果它不告知用户它在做什么,您将收到大量的支持电话。因此,请包含消息,告知用户等待输出,因为正在进行计算。如果可能,请尝试指示用户需要等待多长时间。如果执行特定任务时等待应该经常花费很长时间,您可能需要考虑在脚本的输出中集成一些处理指示。
当提示用户输入时,最好也提供过多而不是过少关于要输入的数据类型的信息。这同样适用于参数的检查和随附的使用信息。
Bash 具有 echo 和 printf 命令来为用户提供注释,虽然您现在至少应该熟悉 echo 的使用,但我们将在接下来的章节中讨论更多示例。
echo 内建命令输出其参数,参数之间用空格分隔,并以换行符结尾。返回状态始终为零。echo 接受几个选项
-e:解释反斜杠转义字符。
-n:禁止尾随换行符。
作为添加注释的示例,我们将改进feed.sh和penguin.sh,这两个脚本来自第 7.2.1.2 节
michel ~/test> cat penguin.sh #!/bin/bash # This script lets you present different menus to Tux. He will only be happy # when given a fish. To make it more fun, we added a couple more animals. if [ "$menu" == "fish" ]; then if [ "$animal" == "penguin" ]; then echo -e "Hmmmmmm fish... Tux happy!\n" elif [ "$animal" == "dolphin" ]; then echo -e "\a\a\aPweetpeettreetppeterdepweet!\a\a\a\n" else echo -e "*prrrrrrrt*\n" fi else if [ "$animal" == "penguin" ]; then echo -e "Tux don't like that. Tux wants fish!\n" exit 1 elif [ "$animal" == "dolphin" ]; then echo -e "\a\a\a\a\a\aPweepwishpeeterdepweet!\a\a\a" exit 2 else echo -e "Will you read this sign?! Don't feed the "$animal"s!\n" exit 3 fi fi michel ~/test> cat feed.sh #!/bin/bash # This script acts upon the exit status given by penguin.sh if [ "$#" != "2" ]; then echo -e "Usage of the feed script:\t$0 food-on-menu animal-name\n" exit 1 else export menu="$1" export animal="$2" echo -e "Feeding $menu to $animal...\n" feed="/nethome/anny/testdir/penguin.sh" $feed $menu $animal result="$?" echo -e "Done feeding.\n" case "$result" in 1) echo -e "Guard: \"You'd better give'm a fish, less they get violent...\"\n" ;; 2) echo -e "Guard: \"No wonder they flee our planet...\"\n" ;; 3) echo -e "Guard: \"Buy the food that the Zoo provides at the entry, you ***\"\n" echo -e "Guard: \"You want to poison them, do you?\"\n" ;; *) echo -e "Guard: \"Don't forget the guide!\"\n" ;; esac fi echo "Leaving..." echo -e "\a\a\aThanks for visiting the Zoo, hope to see you again soon!\n" michel ~/test> feed.sh apple camel Feeding apple to camel... Will you read this sign?! Don't feed the camels! Done feeding. Guard: "Buy the food that the Zoo provides at the entry, you ***" Guard: "You want to poison them, do you?" Leaving... Thanks for visiting the Zoo, hope to see you again soon! michel ~/test> feed.sh apple Usage of the feed script: ./feed.sh food-on-menu animal-name |
有关转义字符的更多信息,请参见第 3.3.2 节。下表概述了 echo 命令识别的序列
表 8-1. echo 命令使用的转义序列
序列 | 含义 |
---|---|
\a | 报警 (响铃)。 |
\b | 退格。 |
\c | 禁止尾随换行符。 |
\e | 转义符。 |
\f | 换页符。 |
\n | 换行符。 |
\r | 回车符。 |
\t | 水平制表符。 |
\v | 垂直制表符。 |
\\ | 反斜杠。 |
\0NNN | 八位字符,其值是八进制值 NNN(零到三个八进制数字)。 |
\NNN | 八位字符,其值是八进制值 NNN(一到三个八进制数字)。 |
\xHH | 八位字符,其值是十六进制值(一个或两个十六进制数字)。 |
有关 printf 命令及其允许您格式化输出的方式的更多信息,请参阅 Bash 信息页。请记住,不同版本的 Bash 之间可能存在差异。