Linux
bash + 驗證是否存在以多種組合結尾的文件
我們可以有
/tmp/file.1
or/tmp/file.43.434
or/tmp/file-hegfegf
,等等那麼我們如何在 bash 中驗證是否
/tmp/file*
存在?我們嘗試
[[ -f "/tmp/file*" ]] && echo "file exists"
但以上不起作用
如何解決?
我會使用其中一個
find
或一個for
循環來辨識這種情況。範例 #1
find
(使用 GNU 擴展來限制搜尋空間):# First try with no matching files [ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no # "no" # Create some matching files and try the same command once more touch /tmp/file.1 /tmp/file.43.434 /tmp/file-hegfegf [ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no # "yes"
Example #2 帶
for
循環found= for file in /tmp/file* do [ -f "$file" ] && found=yes && break done [ yes = "$found" ] && echo yes || echo no # No files "no", otherwise "yes"