2014-10-12 68 views
1

請幫我理解第二行。 我的理解增加了公共庫,但我不明白到底做什麼的,具體而言,[ -f ..命令令人困惑的設置行與-f命令

#!/bin/bash 
[ -f ./scripts/commons.sh ] && source ./scripts/commons.sh || 
    { echo "Failed to source common.sh. Check that you are on l2ver dir." && exit 1; } 

回答

0

-f命令檢查文件是否退出。 []是bash中的測試語句。

&&確保第二個命令source ./scripts/commons.sh只有在第一個命令成功終止時纔會執行。即是文件./scripts/commons.sh存在

例如,如果存在文件

$ls test 
test 
$[ -f test ] 
$echo $? 
0 
$[ -f test ] && echo "hello world" 
hello world 

如果不是

$[ -f test ] 
$echo $? 
1 
$[ -f test ] && echo "hello world" 
$ 
0

這意味着它的文件./scripts/commons.sh存在
那麼,如果它存在,文件將被處理source命令其參數存在且是一個普通文件
Read this

1

-f測試(例如,是不是一個目錄)。

在片斷你上述共享,它會檢查是否./scripts/commons.sh是一個文件,然後source的IT代碼(即,在同一外殼執行它)。

0

基本上它是唯一一個線由於邏輯表達式。 -f是一個bash縮短測試,如果該文件存在。 source命令負責從./scripts/commons.sh獲取變量。

您有一個邏輯表達式,如:A和B或C.如果./scripts/commons.sh不存在,則echo出現錯誤並且腳本終止。

還有許多其他的bash內置文件測試。請看下面的列表:

 -b FILE 
       FILE exists and is block special 
     -c FILE 
       FILE exists and is character special 
     -d FILE 
       FILE exists and is a directory 
     -e FILE 
       FILE exists 
     -f FILE 
       FILE exists and is a regular file 
     -g FILE 
       FILE exists and is set-group-ID 
     -G FILE 
       FILE exists and is owned by the effective group ID 
     -h FILE 
       FILE exists and is a symbolic link (same as -L) 
     -k FILE 
       FILE exists and has its sticky bit set 
     -L FILE 
       FILE exists and is a symbolic link (same as -h) 
     -O FILE 
       FILE exists and is owned by the effective user ID 
     -p FILE 
       FILE exists and is a named pipe 
     -r FILE 
       FILE exists and read permission is granted 
     -s FILE 
       FILE exists and has a size greater than zero 
     -S FILE 
       FILE exists and is a socket 
     -t FD 
       file descriptor FD is opened on a terminal 
     -u FILE 
       FILE exists and its set-user-ID bit is set 
     -w FILE 
       FILE exists and write permission is granted 
     -x FILE 
       FILE exists and execute (or search) permission is granted