如何使用test -f
和路径中的通配符来查看文件是否存在?如何在路径中使用通配符“测试-f”?
这工作:
test -f $PREFIX/lib/python3.6/some_file
这不起作用(我究竟做错了什么?):
test -f $PREFIX/lib/python*/some_file
我需要一个非零退出代码,如果该文件不存在。
如何使用test -f
和路径中的通配符来查看文件是否存在?如何在路径中使用通配符“测试-f”?
这工作:
test -f $PREFIX/lib/python3.6/some_file
这不起作用(我究竟做错了什么?):
test -f $PREFIX/lib/python*/some_file
我需要一个非零退出代码,如果该文件不存在。
展开通配符数组,然后检查第一个元素:
f=($PREFIX/lib/python*/some_file)
if [[ -f "${f[0]}" ]]; then echo "found"; else echo "not found"; fi
unset f
从test
手册页:
-f file True if file exists and is a regular file
意味着test -f <arg>
预计arg
是一个单文件。如果路径中的通配符导致多个文件,则会引发错误。使用通配符:)
您需要遍历文件作为test -f
只用一个文件工作时
尝试迭代。我会用一个shell函数为:
#!/bin/sh
# test-f.sh
test_f() {
for fname; do
if test -f "$fname"; then
return 0
fi
done
}
test_f "[email protected]"
然后试运行可能是
$ sh -x test-f.sh
$ sh -x test-f.sh doesnotexist*
$ sh -x test-f.sh *
@ user3439894明显。感谢您的注意和报告。我修好了它。 – ndim
当你说“这不起作用“你的意思是错误发生,或者当你期望是真的时它返回错误? – pedromss
您可能对'failglob'选项感兴趣。 – chepner