我是 Bash 腳本的新手,一直在撰寫腳本來檢查不同的日志檔案是否存在,我有點卡在這里。
clientlist=/path/to/logfile/which/consists/of/client/names
# I grepped only the client name from the logfile,
# and piped into awk to add ".log" to each client name
clients=$(grep -i 'list of client assets:' $clientlist | cut -d":" -f1 | awk '{print $NF".log"}')
echo "Clients : $clients"
#For example "Clients: Apple.log
# Samsung.log
# Nokia.log
# ...."
export alertfiles="*_$clients" #path/to/each/client/logfiles
for file in $alertfiles
do
# I will test each ".log" file of each client, if it exists or not
test -f "$file" && echo $file exists || { echo Error: $file does not exist && exit; }
done
上面的代碼從日志檔案中獲取客戶端名稱,并在每個客戶端欄位的末尾awk添加了 , 。.log從輸出中,我試圖eachclientname.log從每個欄位傳遞到一個變數,即alertfiles,并構造一個路徑來測驗檔案是否存在。
客戶的數量是不確定的,并且可能會不時變化。
我擁有的代碼整體回傳客戶端名稱:
"Clients: Apple.log
Samsung.log
Nokia.log
....."
我不確定如何將每個客戶端名稱一一傳遞到回圈中,以便測驗每個客戶端名稱日志檔案是否存在。我怎樣才能做到這一點?
export alertfiles="*_$clients" #path/to/each/client/logfiles
我想在$clients這里一一列出輸出,以便它一一回傳所有客戶端名稱,而不是作為一個整體,我可以將它傳遞到回圈中,因此客戶端日志檔案名被一一檢查。
uj5u.com熱心網友回復:
使用bash 陣列。
(順便說一句:我無法對此進行測驗,因為您沒有提供輸入資料的示例)
clientlist=/path/to/logfile/which/consists/of/client/names
logfilebase=/path/to/where/the/logfiles/should/exist
declare -a clients=($(grep -i 'list of client assets:' $clientlist | cut -d":" -f1))
for item in "${clients[@]}"; do
if [ -e ${logfilebase}/${item}.log ]; then
echo "$item exists"
else
echo "$item does not exist - quit"
exit 1
fi
done
uj5u.com熱心網友回復:
真的不清楚你在問什么。$clients已經是一個可以回圈的標記串列,盡管將其保存在變數中似乎是不必要的記憶體浪費。
另外,為什么要遍歷通配符然后檢查檔案是否存在?如果通配符上沒有匹配項,您可以確保該nullglob檔案根本不回圈。
我猜您的實際問題是如何檢查您指定的目錄中是否存在日志檔案。
我也重構了您的代碼以在 Awk中執行grep和。cut查看無用的使用grep
shopt -s nullglob # bash feature
awk -F: 'tolower($0) ~ /list of client assets:/ {
print(tolower($1).log))' "$clientlist" |
while read -r client; do
# some heavy guessing here
for file in path/to/each/"$client"/logfiles/*; do
test -f "$file" && echo "$file" exists || { echo "Error: $file does not exist" && exit; }
done
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530018.html
