bash参数解析
(2020-04-17 17:10:20)
标签:
bash参数解析 |
分类: linux |
1.特殊特殊变量
#!/bin/bash
# file test.sh
echo $0 #
当前脚本的文件名(间接运行时还包括绝对路径)。
echo $1 # 传递给脚本或函数的参数。n
是一个数字,表示第几个参数。例如,第一个参数是 $1 。
echo $# #
传递给脚本或函数的参数个数。
echo $* #
传递给脚本或函数的所有参数。
echo $@ #
传递给脚本或函数的所有参数。被双引号 (" ") 包含时,与 $* 不同,下面将会讲到。
echo $? #
上个命令的退出状态,或函数的返回值。
echo $$ # 当前 Shell 进程
ID。对于 Shell 脚本,就是这些脚本所在的进程 ID。
echo $_ #
上一个命令的最后一个参数
echo $! # 后台运行的最后一个进程的 ID
号
root@VM-130-124-debian:~/temp# sh test.sh abc def 123
test.sh
abc
3
abc def 123
abc def 123
0
20775
/bin/sh
$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号 ("") 包含时,都以"$1""$2" … "$n"
的形式输出所有参数。
但是当它们被双引号 ("") 包含时,"$*"会将所有的参数作为一个整体,以"$1 $2 …
$n"的形式输出所有参数;"$@"会将各个参数分开,以"$1""$2" … "$n" 的形式输出所有参数。
2.依次分割输入参数
#!/bin/bash
# file params.sh
printf "The complete list is %s\n" "$$"
printf "The complete list is %s\n" "$!"
printf "The complete list is %s\n" "$?"
printf "The complete list is %s\n" "$*"
printf "The complete list is %s\n" "$@"
printf "The complete list is %s\n" "$#"
printf "The complete list is %s\n" "$0"
printf "The complete list is %s\n" "$1"
printf "The complete list is %s\n" "$2"
root@VM-130-124-debian:~/temp# bash params.sh 123456 QQ
The complete list is 14961
The complete list is
The complete list is 0
The complete list is 123456 QQ
The complete list is 123456
The complete list is QQ
The complete list is 2
The complete list is params.sh
The complete list is 123456
The complete list is QQ
3.getopt 处理参数
#!/bin/bash
# file proxychains4.sh
GETOPTOUT=`getopt ab:c:d "$@"`
root@VM-130-124-debian:~/temp# sh proxychains4.sh -a -b t2 -c
t3 -d
发现 -a 选项
发现 -b 选项
-b 选项的参数值是:t2
发现 -c 选项
-c 选项的参数值是:t3
发现 -d 选项
getopt ab:c:d "$@" 中的 abcd 分别代表四个选项,后面带有冒号的表示选项需要参数值
后一篇:shell中将命令结果赋值给变量