對shell中常見參數及判斷命令介紹

今天小編就爲大家分享一篇對shell中常見參數及判斷命令介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

Shell常用特殊變量

經常會在shell命令中,看到$0, $#, $*, $@, $?, $$這樣的取值,這些代表什麼呢?

變量 含義
$0 當前腳本的文件名
$n 傳遞給腳本或函數的參數。n 是一個數字,表示第幾個參數。例如,第一個參數是$1,第二個參數是$2
$# 傳遞給腳本或函數的參數個數
$* 傳遞給腳本或函數的所有參數
$@ 傳遞給腳本或函數的所有參數。被雙引號(” “)包含時,與 $* 稍有不同
$? 上個命令的退出狀態,或函數的返回值。成功返回0,失敗返回1
$$ 當前Shell進程ID。對於 Shell 腳本,就是這些腳本所在的進程ID

$* 和 $@ 都是將參數一個一個返回

"$*"將所有參數當做一個整體字符串返回 , "$@"將參數一個一個返回

常用判斷參數

在shell命令文件中還經常會看到類似與if [ -z "${SPARK_HOME}" ]; then這樣的判斷語句?是不是也和我一樣很疑惑-z是什麼含義?

下面是幾個常見的參數,供查詢使用:

-a file exists. 
-b file exists and is a block special file. 
-c file exists and is a character special file. 
-d file exists and is a directory. 
-e file exists (just the same as -a). 
-f file exists and is a regular file. 
-g file exists and has its setgid(2) bit set. 
-G file exists and has the same group ID as this process. 
-k file exists and has its sticky bit set. 
-L file exists and is a symbolic link. 
-n string length is not zero. 
-o Named option is set on. 
-O file exists and is owned by the user ID of this process. 
-p file exists and is a first in, first out (FIFO) special file or named pipe. 
-r file exists and is readable by the current process. 
-s file exists and has a size greater than zero. 
-S file exists and is a socket. 
-t file descriptor number fildes is open and associated with a terminal device. 
-u file exists and has its setuid(2) bit set. 
-w file exists and is writable by the current process. 
-x file exists and is executable by the current process. 
-z string length is zero. 

判斷命令

shell中除了有上邊這樣用來判斷文件是否存在的參數,當然還有判斷兩個數是否相等這樣更常規的命令

例如,if [ $# -gt 0 ]這樣判斷傳入參數個數是否爲0

命令 含義
-eq 等於
-ne 不等於
-gt 大於
-lt 小於
ge 大於等於
le 小於等於

以上這篇對shell中常見參數及判斷命令介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章