将命令行的参数给筛选出来
代码如下:
[root@youyan 19:58:08~/test]# vim test02.sh #!/bin/bash while getopts a:b:c: opt;do #abc表示参数 case $opt in a) a=$OPTARG;; #$OPTARG代表参数后面的值 b) b=$OPTARG;; c) c=$OPTARG;; *) echo "illegal";; esac done echo $a echo $b echo $c
结果如下
[root@youyan 20:02:45~/test]# bash test02.sh -a 1 -b 2 -c 3 1 2 3
另外,还可以使用if语句对其进行判断,是否为空,如果为空则退出。代码如下
#!/bin/bash while getopts a:b:c: opt;do case $opt in a) a=$OPTARG;; b) b=$OPTARG;; c) c=$OPTARG;; *) echo "illegal";; esac done if [[ -z "${a}" || -z "${b}" || -z "${c}" ]]; then #abc收到参数传过来的值后,再次检查是否为空,如果为空,则退出 echo "illegal"; exit 1 fi echo $a echo $b echo $c
转载于:https://blog.51cto.com/dashui/1898402