我有一個功能來檢查路徑中是否存在檔案
file_exists ()
{
[ -f $1 ]
}
我的要求是檢查位于不同路徑中的多個檔案(在本例中為 2 個檔案)。如果兩個檔案都存在,那么只有我應該進入下一步。
在這里,我想到了將 IF 條件與 AND 門一起使用,但無法得到我期望的結果。
該函式永遠不會從 IF 條件中呼叫。
有人可以幫我解決我的要求嗎?我怎樣才能寫得更好?
if [[ $(file_exists /opt/file1) == "0" && $(file_exists /temp/file2) == "0" ]];
then
#next steps code here
else
echo " some files missing"
fi
uj5u.com熱心網友回復:
當你使用$(command)
時,它被替換為命令的標準輸出,而不是它的退出狀態。由于您的函式不會產生任何輸出,因此它永遠不會等于"0"
.
您不需要[[
測驗退出狀態,該if
命令會自行完成。
if file_exists /opt/file1 && file_exists /tmp/file2
then
# next steps here
else
echo "Some files missing"
fi
uj5u.com熱心網友回復:
如果您想節省重寫同一個呼叫的時間。您可以使用一個函式來測驗所有檔案是否存在:
all_files_exist ()
{
while [ $# -gt 0 ]
do
[ -f "$1" ] || return 1
shift
done
}
if all_files_exist /opt/file1 /temp/file2
then
printf 'All files exist.\n'
else
printf 'Some files are missing.\n' >&2
exit 1
fi
uj5u.com熱心網友回復:
簡單的
[ -f /opt/file1 -a -f /opt/file2 ] && { echo "All files exist"; } || { echo "Some files missing"; }
帶功能
#!/bin/bash
allExist(){
for file in $@
do
[ ! -f $file ] && return 1
done
return 0
}
FILES="/opt/file1 /opt/file2"
allExist $FILES && {
echo "All files exist"
} || {
echo "Some files missing"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470323.html
上一篇:Javascript-是否可以將2個值放入函式的1個引數中?
下一篇:重復printf()