Bash If语句指定错误



我没有正确地指定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个文件。

我一直在使用很多其他的线程,比如这个和这个来寻找解决方案,但没有太多的运气。任何帮助都非常感谢!

[[ ]]条件表达式中,-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"

我还建议使用小写或混合大小写的变量名,以避免与许多具有特殊含义的全大写名称冲突。

最新更新