Shell中的option模块知识解析
最近,公司要求写shell脚本,本想开一瓶82年的雪碧,犯难了,事情是这样的... ...具体需求大概是这样的,需要执行脚本的形式是这样的... ./test.sh 1 camera 这需要两个参数啊!!!
我们已经见过$* 和 $1, $2 ... $9 等特殊变量,这些特殊变量包含了用户从命令行输入的参数。但是在编写更复杂的程序时,您可能会发现您需要更多的自定义的选项。通常的惯例是在所有可选的参数之前加一个减号,后面再加上参数值 (比如文件名)。
有好多方法可以实现对输入参数的分析,但是下面的使用case表达式的例子无遗是一个不错的方法。
#!/bin/sh # 核心代码: case $1 in -h) xx1;shift 1;; # function help is called -f) xx1;shift 1;; # variable opt_f is set -l) xx1;shift 2;; # -l takes an argument -> shift by 2 --) shift;break;; # end of options -*) echo "error: no such option $1. -h for help";exit 1;; *) break;; esac
例子:
#! /bin/sh case $1 in 1) ./脚本| sed -n '2p' | awk '{print $4}';; 2) ./脚本| sed -n '2p' | awk '{print $6}';; 3) ./脚本| sed -n '2p' | awk '{print $8}';; 4) ./脚本| sed -n '2p' | awk '{print $10}';; esac
执行起来:./test_msg 1
项目实战例子参考:https://www.cnblogs.com/wzhqzm/p/16453836.html#tid-Zn5sxt