Shell特殊变量(Shell $#、$*、$@、$?、$$)的使用
上节我们讲到了$n,它是特殊变量的一种,用来接收位置参数。本节我们继续讲解剩下的几个特殊变量,它们分别是:$#、$*、$@、$?、$$。
Shell特殊变量及其含义
变量 | 含义 |
---|---|
$0 | 当前脚本的文件名。 |
$n(n≥1) | 传递给脚本或函数的参数。n是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。 |
$# | 传递给脚本或函数的参数个数。 |
$* | 传递给脚本或函数的所有参数。 |
$@ | 传递给脚本或函数的所有参数。当被双引号""包含时,$@ 与$*稍有不同,我们将在《Shell$*和$@的区别》一节中详细讲解。 |
$? | 上个命令的退出状态,或函数的返回值,我们将在《Shell$?》一节中详细讲解。 |
$$ | 当前Shell进程ID。对于Shell脚本,就是这些脚本所在的进程ID。 |
下面我们通过两个例子来演示。
1)给脚本文件传递参数
编写下面的代码,并保存为test.sh:
#!/bin/bash echo"ProcessID:$$" echo"FileName:$0" echo"FirstParameter:$1" echo"SecondParameter:$2" echo"Allparameters1:$@" echo"Allparameters2:$*" echo"Total:$#"
运行test.sh,并附带参数:
[mozhiyan@localhostdemo]$../test.shShellLinux
ProcessID:5943
FileName:bash
FirstParameter:Shell
SecondParameter:Linux
Allparameters1:ShellLinux
Allparameters2:ShellLinux
Total:2
2)给函数传递参数
编写下面的代码,并保存为test.sh:
#!/bin/bash #定义函数 functionfunc(){ echo"Language:$1" echo"URL:$2" echo"FirstParameter:$1" echo"SecondParameter:$2" echo"Allparameters1:$@" echo"Allparameters2:$*" echo"Total:$#" } #调用函数 funcJavahttp://c.biancheng.net/java/
运行结果为:
Language:Java
URL:http://c.biancheng.net/java/
FirstParameter:Java
SecondParameter:http://c.biancheng.net/java/
Allparameters1:Javahttp://c.biancheng.net/java/
Allparameters2:Javahttp://c.biancheng.net/java/
Total:2
到此这篇关于Shell特殊变量(Shell$#、$*、$@、$?、$$)的使用的文章就介绍到这了,更多相关Shell特殊变量内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!