bash Bash中$#有什么用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36007240/
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 is the use of $# in Bash
提问by Lawrence Loh
I am very new to Bash scripting, can someone explain to me how the $# and $? work in the following code?
我对 Bash 脚本很陌生,有人可以向我解释 $# 和 $ 的用法吗?在以下代码中工作?
#!/bin/bash
ARGS=3 # Script requires 3 arguments.
E_BADARGS=85 # Wrong number of arguments passed to script.
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename # Builtin variables:
# There are some useful builtin variables, like
echo "Last program's return value: $?"
echo "Script's PID: $$"
echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "The script's name: script.sh 1
"
echo "Script's arguments separated into different variables: ..."
` old-pattern new-pattern filename"
exit $E_BADARGS
fi
old_pattern=
new_pattern=
if [ -f "" ]
then
file_name=
else
echo "File \"\" does not exist."
exit $E_BADARGS
fi
exit $?
回答by Thomas Ayoub
回答by user000001
From https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
来自https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
$#
Expands to the number of positional parameters in decimal.
$?
Expands to the exit status of the most recently executed foreground pipeline.
$#
扩展到十进制位置参数的数量。
$?
扩展到最近执行的前台管道的退出状态。
回答by ClaudioM
$#
shows the number of the script's arguments
$?
shows the last script's return value
$#
显示脚本参数的数量
$?
显示最后一个脚本的返回值
about arguments: echo "ARG[$#]"
before if
and then execute the script like
关于参数:echo "ARG[$#]"
之前if
然后执行脚本,如
#shell>ls
file1.txt g inpu nodes_list
#shell>echo $?
0
#shell>ls FileNameNotFound
ls: FileNameNotFound: No such file or directory
#shell> echo $?
1
the ouput will be
输出将是
##代码##and so on
等等
the ouput of $?
could be also used on the command line:
的输出$?
也可以在命令行上使用: