2011-02-17 18:53:26 +0000 2011-02-17 18:53:26 +0000
83
83
Advertisement

Linux中的$*和$#是什么?

Advertisement

Linux中以下环境变量是什么意思?

1.什么是$*(美元符号后加星号)? 2. 什么是$#(哈希号/数字符号/八叉号/磅号旁边的美元符号)?

Advertisement
Advertisement

答案 (2)

117
117
117
2011-02-17 18:59:34 +0000

这里

$# Stores the number of command-line arguments that 
      were passed to the shell program.
$? Stores the exit value of the last command that was 
      executed.
$0 Stores the first word of the entered command (the 
      name of the shell program).
$* Stores all the arguments that were entered on the
      command line ($1 $2 ...).
"$@" Stores all the arguments that were entered
      on the command line, individually quoted ("$1" "$2" ...).

所以基本上,$#是你的脚本执行时给出的参数数。$*是一个包含所有参数的字符串。例如,$1是第一个参数,以此类推。如果你想在脚本中访问一个特定的参数,这很有用。

正如Brian评论的那样,这里有一个简单的例子。如果你运行以下命令。

./command -yes -no /home/username
  • $# = 3
  • $* = -yes -no /home/username
  • $@ = 数组。{"-yes", "-no", "/home/username"}
  • $0 = ./command, $1 = -yes等等。

这些都是 POSIX 标准 的一部分,所有符合标准的 shell 都应该支持。以下是POSIX标准对每个特殊参数的定义,供参考。请注意有三个附加变量:$-$$$!

$@:

从1开始扩展到位置参数。当扩展发生在双引号内,且进行了字段分割(见 字段分割 )时,每个位置参数应作为一个单独的字段进行扩展,规定第一个参数的扩展仍应与原字的起始部分相接(假设扩展后的参数嵌入在一个字内),最后一个参数的扩展仍应与原字的最后部分相接。如果没有位置参数,则’@‘的扩展应产生零字段,即使’@‘是双引号。

$*:

从1开始扩展到位置参数。当扩展发生在一个双引号字符串中时(见 双引号 ),它应扩展到一个单一字段,每个参数的值用IFS变量的第一个字符分隔,如果IFS未设置,则用a分隔。如果IFS被设置为空字符串,这不等于取消设置,它的第一个字符不存在,所以参数值是连在一起的。

$#:

展开到位置参数的十进制数。命令名(参数0)不应计入’#‘给出的数字中,因为它是特殊参数,不是位置参数。

$?:

展开到最近管道的十进制退出状态(见 管道 )。

$-:

(连字符。)扩展到当前的选项标志(由 set 特殊内置命令或shell隐含指定的单字母选项名)。

$$:

扩展到被调用shell的十进制进程ID。在子shell中(见shell执行环境),’$‘应扩展为与当前shell相同的值。

$!:

展开到当前shell最近执行的后台命令(见 列表 )的十进制进程ID。例如,从子shell执行的后台命令不影响当前shell环境中"$!"的值)。对于流水线来说,进程ID是流水线中最后一条命令的ID。

$0:

(零。)扩展为shell或shell脚本的名称。请参阅 sh ,了解如何推导这个名称的详细说明。

0
0
0
2018-09-24 05:34:09 +0000

$#代表参数的数量。

[root@baymax ~]# set -- a
[root@baymax ~]# echo $#
1

[root@baymax ~]# set -- a b c
[root@baymax ~]# echo $#
3
Advertisement

相关问题

6
10
5
37
2
Advertisement
Advertisement