向脚本传递参数:
./script_name.sh var0 var1 var2
脚本内取参:
$0: 文件名
$1: 第1个参数
$2: 第2个参数
[root@k8s-master test0]# cat test8.sh
#!/bin/bash
echo "params:"
echo "script name: $0";
echo "first param: $1";
echo "second parma: $2";
[root@k8s-master test0]# ./test8.sh hello world ni hao
params:
script name: ./test8.sh
first param: hello
second parma: world
[root@k8s-master test0]#
特殊字符:
$#: 参数个数
$*: 以一个单字符串显示所有参数。如""括起来,以"$1 $2 ... $n"形式输出所有参数
$$: 当前进程ID号
$!: 后台运行的最后一个进程ID号
$@: 与$*相同。但是使用时加",在引号中返回每个参数。如"$@",以"$1" "$2" ... "$n"形式输出所有参数。
$-: 与set命令功能相同,显示shell使用的当前选项。
$?: 显示最后命令的退出状态,0表示无错,其他任何值表示有错。
[root@k8s-master test0]# sh test9.sh 1 2 3 4 5
first: 1
num: 5
string: 1 2 3 4 5
string split: 1 2 3 4 5
current pid: 113417
last pid:
exit status: 0
$*:
-- $* --
1 2 3 4 5
-- $@ --
1
2
3
4
5
[root@k8s-master test0]# cat test9.sh
#!/bin/bash
echo "first: $1";
echo "num: $#";
echo "string: $*";
echo "string split: $@";
echo "current pid: $$";
echo "last pid: $!"
echo "exit status: $?";
echo '$*:'
echo "-- \$* --"
for i in "$*"; do
echo $i
done
echo "-- \$@ --"
for i in "$@"; do
echo $i;
done
[root@k8s-master test0]#