bash $做什么?和 $# 代表 Shell 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11323847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What do $? and $# stand for in Shell Script?
提问by xczzhh
I have the following two chunks of code, I am not so sure what $? and $# stand for. Please help.
我有以下两段代码,我不太确定 $? 和 $# 代表。请帮忙。
CODE ONE
代码一
#!/bin/bashUSERID=""
/bin/id $USERID 2>/dev/null
[ $? -eq 0 ] && echo "User found" || echo "User not found"
/bin/id -g $USERID 2>/dev/null
[ $? -eq 0 ] && echo "Group found" || echo "Group not found" `
$ cat > mtable
CODE TWO
代码二
#!/bin/sh
#
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : ##代码## number"
echo "Use to print multiplication table for given number"
exit 1
fi
n=
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done
Thank you
谢谢
回答by Abhijeet Rastogi
$?gives you the return code of the previous command executed.
$?为您提供上一个执行命令的返回码。
$#give you the number of command line arguments given to the script.
$#给你提供给脚本的命令行参数的数量。
So, basically that if condition checks if the number of arguments given were proper or not.
所以,基本上,如果条件检查给定的参数数量是否正确。
回答by Miquel
Have a look at the man page for bash:
看看手册页bash:
$# Expands to the number of positional parameters in decimal
$? Expands to the status of the most recently executed foreground pipeline.
$# 扩展为十进制位置参数的个数
$? 扩展到最近执行的前台管道的状态。

