shell特殊变量

特殊变量列表

变量含义
$0当前脚本的文件名,包含路径
$n传递给脚本或者函数的参数. n 是一个数字,表示第几个参数。例如,第一个参数是 1 2
$#传递给脚本或者函数的参数的个数
$*传递给脚本或函数的所有参数
$@传递给脚本或函数的所有参数
$?上个命令的退出状态,或函数的返回值
$!上一个执行命令的PID
$_在此之前执行的命令或者脚本的最后一个参数

实例

$ cat shell.sh 
#!/bin/bash 

echo "the file name is: $0" 
echo "the 1st argument is: $1" 
echo "the 2nd argument is: $2" 
echo "number of argument is: $#" 
echo "state of last command is: $?" 
echo "PID of last command is: $!" 
echo "PID of current command is: $$" 
echo "the last argument is: $_" 

执行结果:
$ ./shell.sh shell test 
the file name is: ./shell.sh   //即会带上执行脚本时用的路径.
the 1st argument is: shell 
the 2nd argument is: test 
number of argument is: 2 
state of last command is: 0 
PID of last command is: 
PID of current command is: 31437 
the last argument is: PID of current command is: 31437 

注意区别$*与$@
$*与$@都表示的是传递给脚本或函数的所有参数。
不被双引号(” “)包含时,都以”$1” “$2” … “$n” 的形式输出所有参数。
但是当它们被双引号(” “)包含时,”$*” 会将所有的参数作为一个整体,以”$1 $2 … $n”的形式输出所有参数;”$@” 会将各个参数分开,以”$1” “$2” … “$n” 的形式输出所有参数。

cat ./shell.sh 
#!/bin/bash 

echo "all the arguments are (result from \$*): $*" 
echo "all the arguments are (result from \$@): $@" 
echo "all the arguments are (result from \"\$*\"): "$*"" 
echo "all the arguments are (result from \"\$@\"): "$@"" 

echo "each result from \$*:" 
for i in $* 
do 
    echo "$i" 
done 

echo "each result from \$@:" 
for i in $@ 
do 
        echo "$i" 
done 

echo "each result from \"\$*\":" 
for i in "$*" 
do 
        echo "$i" 
done 


echo "each result from \"\$@\":" 
for i in "$@" 
do 
        echo "$i" 
done 

执行结果: 
$ ./shell.sh shell test 
all the arguments are (result from $*): shell test 
all the arguments are (result from $@): shell test 
all the arguments are (result from "$*"): shell test 
all the arguments are (result from "$@"): shell test 
each result from $*: 
shell 
test 
each result from $@: 
shell 
test 
each result from "$*": 
shell test 
each result from "$@": 
shell 

关于$?
获取上一个命令的退出状态。所谓退出状态,就是上一个命令执行后的返回结果。
退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。不过,也有一些命令返回其他值,表示不同类型的错误。
0 表示运行成功
2 表示权限拒绝
1~125 表示运行失败, 脚本命令/系统命令/参数传递错误
126 找到了该命令, 但是取法执行
127 未找到要运行的命令
128 命令被系统强制结束

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值