如何使用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