linux中 $?和$#怎么理解,希望说详细点,谢谢

希望可以举例子··谢谢

$?表示最后执行命令的返回,0表示成功,非0表示失败。另外逻辑运算也会有返回,比如[ $1 -eq 2 ] && echo $?中,如果参数1等于2,则为true,返回0,反之,[ $1 -eq 2 ] || echo $?,如参数1不等于2,则为false,返回的结果就是1。

$#表示输入参数的个数,如运行bash xxx.sh a b c,即输入3个参数到xxx.sh运行,$#就是3。
顺便说,这时$1为a,$2为b,$3为c,$0为xxx.sh。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-14
$?:表示上一条指令执行是否成功,0表示成功
$#:表示参数的个数追问

是否可以举例,谢谢

追答

[root@master ~]# cat test.sh
#!/bin/bash
echo "the argument amount \$# is:$#"
echo "the argument list are: $@"
echo "excecute date command"
date
if [ $? -eq 0 ];then
echo " \$? is $?,execute status is sucessful"
fi
[root@master ~]#
[root@master ~]# ./test.sh aa bb cc
the argument amount $# is:3 //参数个数
the argument list are: aa bb cc //参数列表
excecute date command
Tue May 14 02:47:46 EDT 2013 //date 执行结果
$? is 0,execute status is sucessful //$?状态码为0.表示上一个命令date执行成功
[root@master ~]#

本回答被提问者采纳
第2个回答  2013-05-14
$?: 命令执行正确,会返回状态值0; 错误有其他的状态值.
例如: 你在输入 ls /root 完了之后 echo $? 测试下 再输入 ls /roott 再输入 echo $? 测试下

$#: 参数的个数
例如: 你写了一个脚本,脚本后面有传参, ./shell.sh param1 param2 此时$0 为脚本本身 $1为第一个参数 $2为第二个参数 以此类推 可到$9 而$#为 传参的总个数
相似回答