2013-11-23 52 views
1

我有以下bash代碼編寫來檢測SSL證書是否存在,如果是,跳過創建一個。檢測if語句中的多個文件

我需要擴展檢測到的文件列表,以便其中任何一個的存在將跳過創建SSL證書。

文件的完整列表是「trailers.cer」或「trailers.key」或「trailers.pem」

的alterntaive方法檢測後,提示用戶,詢問他們是否要創建SSL certifictes

file="assets/certificates/trailers.cer" 
if [ -f "$file" ]; then 
echo 'SSL Certificates already created' 
else 
openssl req -new -nodes -newkey rsa:2048 -out ./assets/certificates/trailers.pem -keyout ./assets/certificates/trailers.key -x509 -days 7300 -subj "/C=US/CN=trailers.apple.com" 
openssl x509 -in ./assets/certificates/trailers.pem -outform der -out ./assets/certificates/trailers.cer && cat ./assets/certificates/trailers.key >> ./assets/certificates/trailers.pem 
fi 

回答

1

你可以把多個條件的if使用多個test||這樣的:

if test -f "$path1" || test -f "$path2" || test -f "$path3"; then 
    ... 
fi 

當有許多文件,使用數組可以更容易和更具有可讀性,就像這樣:

#!/bin/bash 

basedir=assets/certificates 
files=(trailers.cer trailers.key trailers.pem) 

found= 
for file in ${files[@]}; do 
    path="$basedir/$file" 
    if [ -f "$path" ]; then 
     echo SSL Certificates already created 
     found=1 
     break 
    fi 
done 

if test ! "$found"; then 
    openssl req -new -nodes -newkey rsa:2048 -out ./assets/certificates/trailers.pem -keyout ./assets/certificates/trailers.key -x509 -days 7300 -subj "/C=US/CN=trailers.apple.com" 
    openssl x509 -in ./assets/certificates/trailers.pem -outform der -out ./assets/certificates/trailers.cer && cat ./assets/certificates/trailers.key >> ./assets/certificates/trailers.pem 
fi 
+0

'-o'已棄用;使用'test -f「$ path1」||測試-f「$ path2」||測試-f「$ path3」'代替。 – chepner

+0

寫在哪裏?在我的Debian測試中帶來的bash中,這在'man test'和'help test'中都沒有提及...... – janos

+0

[POSIX規範](http://pubs.opengroup.org/onlinepubs/9699919799 /utilities/test.html)(請參閱「應用程序使用」部分)將其標記爲過時,這是由於根據使用的其他參數進行解析時存在歧義。 – chepner

2

假設它足以退出整個腳本,

for file in trailers.cer trailers.key /assets/certificates/trailers.pem; do 
    test -f "$file" && exit 1 # or even 0? 
done 
# If you reach through here, none existed 

我改變了項目之一一個絕對路徑只是爲了說明它是如何完成的。如果所有文件的路徑都是相同的,那麼您可以重構以後提供路徑; test -f "/assets/certificates/$file"

+0

謝謝。該選項如何處理文件位於當前工作目錄的不同目錄中?例如/assets/certificates/trailers.pem – user2990773

+0

如果這有幫助,請考慮[接受此答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。謝謝! – tripleee