shell参数解析

简单解析

参数 作用
$@ 全部参数
$* 全部参数
$# 参数个数
$n 第n个参数
1
$@和$*存在一定区别,当两者在""中充当参数时,$@不会对所有参数进行处理;$*会把所有参数合并成一个参数处理

getopt 短参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# test.sh
while getopts ":a:b" opt
do
case $opt in
a)
a=$OPTARG
echo "a is $a";;
b)
echo "b is set";;
?)
echo "getopts param error"
exit 1;;
esac
done

# ./test.sh -b -a 8
":a:b"
最前面的引号:忽略执行错误
a后面引号:表示该标志后有参数
b无引号:表示该标志后无参数

getopts 长参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

# Setup getopt.
long_opts="debug,arg:"
getopt_cmd=$(getopt -o da: --long "$long_opts" \
-n $(basename $0) -- "$@") || \
{ echo -e "\nERROR: Getopt failed. Extra args\n"; exit 1;}

eval set -- "$getopt_cmd"
while true; do
case "$1" in
-d|--debug) echo "debug is true";;
-a|--arg) echo "arg is $2";;
--) shift; break;;
esac
shift
done