![如何測試bash中是否存在一個或多個帶有前綴的檔案?例如 [[-f foo*]]](https://rvso.com/image/178564/%E5%A6%82%E4%BD%95%E6%B8%AC%E8%A9%A6bash%E4%B8%AD%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8%E4%B8%80%E5%80%8B%E6%88%96%E5%A4%9A%E5%80%8B%E5%B8%B6%E6%9C%89%E5%89%8D%E7%B6%B4%E7%9A%84%E6%AA%94%E6%A1%88%EF%BC%9F%E4%BE%8B%E5%A6%82%20%5B%5B-f%20foo*%5D%5D.png)
有沒有辦法使用檔案名稱擴充在一個test
表達,更具體地說,一個bash 條件表達式?
例如:
[[ -f foo* ]] && echo 'found it!' || echo 'nope!';
…。將輸出“沒有!”文件是否foobar
存在於目前目錄中。
並添加一個var
喜歡...
bar=foo*
[[ -f `echo $bar` ]] && echo 'found it!' || echo 'nope!';
…。將輸出“找到了!”如果foobar
檔案存在,但前提是echo $bar
擴充只傳回一個檔案。
答案1
以下假設您不關心 glob 是否符合任何文件,包括區塊特殊文件、字元特殊文件、目錄、符號連結等。
這是以下的理想用例failglob
:
shopt -s failglob
if echo foo* &>/dev/null
then
# files found
else
# no files found
fi
或者,如果您需要文件清單(如果存在):
shopt -s failglob
files=(foo*)
if [[ "${#files[@]}" -eq 0 ]]
then
# no files found
else
# files found
fi
如果找不到文件是錯誤,您可以簡化此操作:
set -o errexit
shopt -s failglob
files=(foo*)
# We know that the expansion succeeded if we reach this line
舊答案
ls
這可能是腳本中(罕見!)的合法使用:
if ls foo* &>/dev/null
then
…
else
…
fi
或者,find foo* -maxdepth 0 -printf ''
。
答案2
基於這個答案,我們可以使用它shopt -s nullglob
來確保在目錄為空時返回註釋:
[[ -n "$(shopt -s nullglob; echo foo*)" ]] && echo 'found it!' || echo 'nope!';
答案3
為了完整起見,這裡有一些使用的範例find
:
#!/bin/bash
term=$1
if find -maxdepth 1 -type f -name "$term*" -print -quit | grep -q .; then
echo "found"
else
echo "not found"
fi
if [ -n "$(find -maxdepth 1 -type f -name "$term*" -print -quit)" ]; then
echo "found"
else
echo "not found"
fi
和一些測試:
user@host > find -type f
./foobar
./bar/foo
./bar/bar
./find_prefixed_files.sh
./ba
user@host > ./find_prefixed_files.sh foo
found
found
user@host > ./find_prefixed_files.sh bar
not found
not found