首页 > 解决方案 > 带有 if 语句的 For 循环在 bash 中没有按预期工作

问题描述

它只打印所有内容的“else”语句,但我知道文件存在它正在寻找的事实。我已经尝试过调整其他一些答案,但我认为这绝对应该有效。

有谁知道我的语法有什么问题?

# Contents of script
for ID_SAMPLE in $(cut -f1 metadata.tsv | tail -n +2);
    do if [ -f ./output/${ID_SAMPLE} ]; then
        echo Skipping ${ID_SAMPLE};
    else
        echo Processing ${ID_SAMPLE};
    fi
done

附加信息

# Output directory
(base) -bash-4.1$ ls -lhS output/
total 170K
drwxr-xr-x 8 jespinoz tigr 185 Jan  3 16:16 ERR1701760
drwxr-xr-x 8 jespinoz tigr 185 Jan 17 18:03 ERR315863
drwxr-xr-x 8 jespinoz tigr 185 Jan 16 23:23 ERR599042
drwxr-xr-x 8 jespinoz tigr 185 Jan 17 00:10 ERR599072
drwxr-xr-x 8 jespinoz tigr 185 Jan 16 13:00 ERR599078

# Example of inputs
(base) -bash-4.1$ cut -f1 metadata.tsv | tail -n +2 | head -n 10
ERR1701760
ERR599078
ERR599079
ERR599070
ERR599071
ERR599072
ERR599073
ERR599074
ERR599075
ERR599076

# Output of script
(base) -bash-4.1$ bash test.sh | head -n 10
Processing ERR1701760
Processing ERR599078
Processing ERR599079
Processing ERR599070
Processing ERR599071
Processing ERR599072
Processing ERR599073
Processing ERR599074
Processing ERR599075
Processing ERR599076


# Checking a directory
(base) -bash-4.1$ ls -l ./output/ERR1701760
total 294
drwxr-xr-x  2 jespinoz tigr   386 Jan 15 21:00 checkpoints
drwxr-xr-x  2 jespinoz tigr     0 Jan 10 01:36 tmp

标签: bashfor-loopif-statement

解决方案


-f用于检查名称是否为文件,但您的所有名称都是目录。用于-d检查。

if [ -d "./output/$ID_SAMPLE" ]
then

如果要检查名称是否存在任何类型,请使用-e.


推荐阅读