我沒有在 bash 中正確指定我的 If 陳述句,但我不確定我到底做錯了什么。
我有數百名參與者完成了不同數量的研究程式,因此他們擁有不同數量的可用檔案。我添加了一個 if 陳述句來指定在處理程序后我們應該為每個參與者找到多少檔案。它應該遍歷每個參與者,根據 ID 為變數分配 3 到 5 之間的值,然后使用該變數的值查找一定數量的檔案。
# SUBJECTS is a concatenated list of IDs
for i in ${SUBJECTS}; do
# Different subjects have a different number of files.
# I want to specify how many files bash should look for based on ID.
# This first if statement should identify whether the current iteration of i matches any of the identified IDs.
# If so, it should specify that bash should be looking for 4 files.
if [[ ${i} -eq "XX001" ||\
${i} -eq "XX002" ||\
${i} -eq "XX003" ]];
then
NFILES=4
# ... and if any iterations of i match these IDs, bash should look for 3 files
elif [[ ${i} -eq "XX004" ||\
${i} -eq "XX005" ]];
then
NFILES=3
# ... and for everyone else, bash should look for 5 files.
else
NFILES=5
fi
# Now, for each participant, iterate through the number of files we expect they should have
for j in `seq -w 1 ${NFILES}` ; do
# ... and check whether a file of this name exists in this location
if [ ! -f "${FILEPATH}/FILENAME_${i}_${j}.nii.gz" ]; then
# If it does not, note which ID and File is missing at the end of this document
echo "${i}; FILE ${j}" >> ${FILEPATH}/MissingFiles.txt
fi
done
done
如果我在沒有第一個 If 陳述句的情況下運行此腳本,它會正確識別參與者存在的檔案,但它也會給出很多誤報(例如,如果參與者只有三個檔案,則輸出將建議檔案 4 和 5丟失了,即使這是預期的)。當我添加 If 陳述句時,計算機似乎出于某種原因假設所有參與者都滿足第一個條件,因此它認為所有參與者都有 4 個檔案。
我一直在使用很多其他執行緒,比如這個和這個來尋找解決方案,但沒有太多運氣。任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
在[[ ]]條件運算式中,-eq運算子進行數字比較,而不是字串比較;你想要=運算子(或等效的==)。
注:語法和語意運營商之間是不同的容易混淆的[[ ]],[ ]和(( ))表達。請參閱此 Unix&Linux 答案和BashFAQ #31。如果您正在為 bash 撰寫(即您的腳本不需要能夠在 dash 或其他一些沒有的 shell 下運行[[ ]]),我建議[ ]完全避免并[[ ]]用于大多數測驗,但(( ))對于嚴格的算術來說是可以的事物。
但是,在這種情況下,由于您將變數與一堆可能的值進行比較,我建議使用一個case陳述句。這就是他們的目的。
case "$i" in
XX001 | XX002 | XX003 )
NFILES=4 ;;
XX004 | XX005 )
NFILES=3 ;;
...
* )
NFILES=5 ;;
esac
您也可以在此處使用 glob 模式,因此XX00[123] )將匹配“XX001”、“XX002”或“XX003”。
我還建議切換到小寫或混合大小寫的變數名稱,以避免與許多具有特殊含義的全大寫名稱發生沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341367.html
