处理用户输入:Shell 脚本的全面指南
1. 处理命令行选项
在编写 Shell 脚本时,处理用户输入是一个重要的任务,其中命令行选项的处理尤为关键。下面将介绍几种处理命令行选项的方法。
1.1 查找选项
命令行选项通常是紧跟在脚本名之后的单个字母,前面带有一个破折号。从表面上看,命令行选项和参数并没有特别之处,它们都出现在命令行中。实际上,你可以用处理命令行参数的方式来处理命令行选项。
1.2 处理简单选项
可以使用 shift 命令和 case 语句来处理简单的命令行选项。以下是一个示例脚本 test15 :
#!/bin/bash
# extracting command line options as parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option";;
esac
shift
done
运行示例:
$ ./test15 -a -b -c -d
Found the -a option
Found the -b option
Found the -c option
-d is not an op
超级会员免费看
订阅专栏 解锁全文
1375

被折叠的 条评论
为什么被折叠?



