shell脚本里“$?”什么意思?

2025-03-21 01:07:39
推荐回答(2个)
回答1:

Linux shell 脚本中, $@ 和$# 分别是:

$@:表示所有脚本参数的内容

$#:表示返回所有脚本参数的个数。

示例:编写如下shell脚本,保存为test.sh

#!/bin/sh

echo "number:$#"

echo "argume:$@"

执行脚本:

./test.sh first_arg second_arg

说明:给脚本提供了两个参数,所以$#输出的结果是2,$@代表了参数的内容!

回答2:

$? 上个命令的退出状态,或函数的返回值。
例子1 :
ls 命令没有找到匹配的结果. 所以返回2 $? 就是2
[root@sg-rhel6-17 etc]# ls /tmp/*.log
ls: cannot access /tmp/*.log: No such file or directory
[root@sg-rhel6-17 etc]# echo $?
2
例子2 :
ls 命令找到了结果. 成功返回0 所以$? 就是0
[root@sg-rhel6-17 etc]# ls /tmp/*.tmp
/tmp/reminder.tmp
[root@sg-rhel6-17 etc]# echo $?
0