Shell中预先定义的特殊变量


$#    命令行上参数的个数,但不包含shell脚本名本身。因此,$#可以给出实际参数的个数。

$?    上一条命令执行后的返回值(也称作 “返回码”、 “退出状态”、“退出码”等)。它是一个十进制数。

$$    当前进程的进程号

$!    上一个后台命令对应的进程号,这是一个由1~5位数字构成的数字串。

$-    由当前shell设置的执行标志名组成的字符串。($ echo $-  #himBH)

$*    表示在命令行中实际给出的所有实参字符串,它并不仅限于9个实参。

$@    它与$*基本功能相同,即表示在命令行中给出的所有实参。但“$@”与“$*”不同。

在《Linux程序设计》里推荐使用 $@,而不是$*,因为$*容易受到IFS变量的影响。

$@	位置参数从 参数1($1) 开始。如果在双引号中进行扩展,则每个参数都会成为一个词,因此 "$@" 与 "$1" "$2" 等效。如果参数有可能包含嵌入空白,那么您将需要使用这种形式("$@")。

$*	位置参数从 参数1($1) 开始。"$*" 扩展实际上是一个词。根据 IFS 进行分割("$*" is one long string and $IFS act as an separator or token delimiters.)。

$@ expanded as "$1" "$2" "$3" ... "$n"
$* expanded as "$1y$2y$3y...$n", where y is the value of $IFS variable

总结:推荐在脚本中使用 "$@" (要记得带上引号)。
参考链接:

《“Shell中预先定义的特殊变量”》 有 3 条评论

  1. shell中的for循环&变量加一操作&字符串的格式化打印
    `
    # for i in {00..23}; do
    > printf ‘%02s %02d\n’ $i $((10#$i+1)) #前面用 ‘%02s’ 后面用 ‘%02d’ 且不能改
    > done
    00 01
    01 02
    02 03
    03 04
    04 05
    05 06
    06 07
    07 08
    08 09
    09 10
    10 11
    11 12
    12 13
    13 14
    14 15
    15 16
    16 17
    17 18
    18 19
    19 20
    20 21
    21 22
    22 23
    23 24
    `

  2. shell中如何对变量进行加一操作? (shell var plus one)
    https://askubuntu.com/questions/385528/how-to-increment-a-variable-in-bash
    https://stackoverflow.com/questions/7245862/how-to-add-values-in-a-variable-in-unix-shell-scripting
    https://stackoverflow.com/questions/4750763/how-do-i-echo-a-sum-of-a-variable-and-a-number

    shell中如何检查参数个数?
    https://stackoverflow.com/questions/4341630/checking-for-the-correct-number-of-arguments
    https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script

    -bash: 08: value too great for base (error token is “08”) #shell中整型变量的进制问题
    http://blog.sina.com.cn/s/blog_699f1fcc01017e1b.html
    http://lists.slug.org.au/archives/slug/2004/08/msg00125.html
    http://www.cnblogs.com/chengyeliang/p/5264526.html
    `
    Shell 默认认为以0开始的数字是八进制数,而八进制不可能出现 08/09 ,所以报错。解决方法就是:
    显示将其指定为10进制。即, $var -> 10#$var

    Numbers starting with leading 0 are Octal numbers (base 8) in many programming languages including C, Perl and shell. Valid octal digits are 0,1,2,3,4,5,6,7 so it barfs if it sees an 8 or a 9. You probably want to work in straight numbers and make a leading 0 in your output format with a sprintf(“%02d”) kind of formatting thing.
    Anything starting with 0x or 0X is a hex number.
    `

    -bash: printf: 08: invalid octal number #shell中printf变量的进制问题
    `
    使用 ‘%02s’ 而不是 ‘%02d’ 来打印类似 08/09 这样的数
    `

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注