简体   繁体   English

Bash检查文件是否存在以及文件扩展

[英]Bash check file existence with file expansion

I want to check if there is a file matching a given pattern exists in the target directory, thus write 我想检查目标目录中是否存在与给定模式匹配的文件,因此写入

data_dir="/home"
sample="HT001"
r1Pattern=".R1.gz"
shopt -s nullglob

if [ -f ${data_dir}/${sample}*combined${r1Pattern} ]
then
  ./myscript
fi

There is NO /home/HT001_combined.R1.gz exist. 不存在/home/HT001_combined.R1.gz But this code kept telling me file exists. 但是这段代码一直告诉我文件存在。 Is there anything I missed? 我有什么想念的吗?

Thanks. 谢谢。

This is because of nullglob mode. 这是因为存在nullglob模式。 Since the file does not exist, the glob expands to nothing. 由于文件不存在,因此glob扩展为空。 And, for an empty arguement, -f will return true if you use [ : 并且,对于空论,如果使用[-f将返回true。

$ empty=
$ [ -f $empty ] && echo yes
yes

You can solve your problem by using the bash [[ instead: 您可以使用bash [[代替:

$ [[ -f $empty ]] && echo yes

[[ generally provides more predictable and friendly behavior. [[通常提供更可预测和友好的行为。

EDIT: 编辑:

Yeah you are right, It seems that actually the glob is not evaluated when using [[ . 是的,您是对的,似乎在使用[[时,实际上并没有评估glob。 The way that comes to mind to do it is more like: 想到的方式更像是:

f=(${data_dir}/${sample}*combined${r1Pattern})
if (( ${#f[@]} == 1 )) && [[ -f ${f[0]} ]]
then
    # ...
fi

This expands the glob into an array, makes sure there is exactly one result, and verifies that it is a regular file. 这会将glob扩展到一个数组中,确保有一个准确的结果,并验证它是常规文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM