基本传参
基本应用如下:
[test@localhost ~]$ cat var1_test.sh
#!/bin/bash
echo 参数0:$0
echo 参数1:$1
echo 参数2:$2
echo 参数3:$3
[test@localhost ~]$ sh var1_test.sh 1 2 3
参数0:var1_test.sh
参数1:1
参数2:2
参数3:3
[test@localhost ~]$
shell中参数处理相关说明:
参数处理 | 说明 |
---|---|
$# | 传递到脚本的参数个数 |
$* | 以一个单字符串显示所有向脚本传递的参数 |
$$ | 脚本运行的当前进程ID号 |
$! | 后台运行 的组后一个进程的ID号 |
$@ | 与$*相同,但是使用时加引号,并在引号中返回每个参数,如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数 |
$- | 显示shell使用的当前选项,与set命令功能相同 |
$? | 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误 |
$*与$@区别
- 相同点:都是引用所有变量
- 不同点:只有在双引号中提现出来。假设在脚本运行时写了三个参数1、2、3,则"*"等价于"1 2 3"(传递了一个参数),而"@"等价于"1" "2" "3"(传递了三个参数)
[test@localhost ~]$ cat var2_test.sh
#!/bin/bash
echo "-------\$*----------"
for i in "$*"
do
echo $i
done
echo "--------\$@---------"
for i in "$@"
do
echo $i
done
[test@localhost ~]$ chmod +x var2_test.sh
[test@localhost ~]$ ./var2_test.sh 1 2 3 4
-------$*----------
1 2 3 4
--------$@---------
1
2
3
4
[test@localhost ~]$
默认参数(变量默认值)
-变量为null
取默认值
- 变量为null时,输出默认值
${var-defaultval}
[test@localhost ~]$ unset var
[test@localhost ~]$ echo ${var}
[test@localhost ~]$ echo ${var-test}
test
[test@localhost ~]$ echo ${var}
[test@localhost ~]$ var=""
[test@localhost ~]$ echo ${var-test}
[test@localhost ~]$ echo ${var}
[test@localhost ~]$
=变量为null时,同时改变变量值
[test@localhost ~]$ unset var1
[test@localhost ~]$ echo ${var1}
[test@localhost ~]$ echo ${var1=test}
test
[test@localhost ~]$ echo ${var1}
test
[test@localhost ~]$ var1=""
[test@localhost ~]$ echo ${var1}
[test@localhost ~]$ echo ${var1=test}
[test@localhost ~]$ echo ${var1}
[test@localhost ~]$
:-变量为null或空字符串,取默认值
${var:-defaultval}
[test@localhost ~]$ unset var2
[test@localhost ~]$ echo ${var2}
[test@localhost ~]$ echo ${var2:-test} #验证变量为null
test
[test@localhost ~]$ echo ${var2}
[test@localhost ~]$ var2=""
[test@localhost ~]$ echo ${var2}
[test@localhost ~]$ echo ${var2:-test} #验证变量为空字符串
test
[test@localhost ~]$ echo ${var2}
[test@localhost ~]$
:=变量为null或空字符串,同时改变变量值
${var:=defaultval}
[test@localhost ~]$ unset var3
[test@localhost ~]$ echo ${var3}
[test@localhost ~]$ echo ${var3:=test} #验证变量为null
test
[test@localhost ~]$ echo ${var3}
test
[test@localhost ~]$ var3=""
[test@localhost ~]$ echo ${var3}
[test@localhost ~]$ echo ${var3:=test} #验证变量为空字符串
test
[test@localhost ~]$ echo ${var3}
test
[test@localhost ~]$
:?变量为null或空字符串报错并退出
[test@localhost ~]$ unset var4
[test@localhost ~]$ echo ${var4}
[test@localhost ~]$ echo ${var4:?error}
-bash: var4: error
[test@localhost ~]$ echo ${var4}
[test@localhost ~]$ var4=""
[test@localhost ~]$ echo ${var4}
[test@localhost ~]$ echo ${var4:?error}
-bash: var4: error
[test@localhost ~]$ echo ${var4}
[test@localhost ~]$
:+变量不为空时使用默认值
与:-相反
[test@localhost ~]$ var5="test"
[test@localhost ~]$ echo ${var5:+defaultest}
defaultest
[test@localhost ~]$ echo ${var5}
test
[test@localhost ~]$