我正在嘗試撰寫一個 shell 腳本來檢查是否存在使用 if 陳述句以 .txt 結尾的檔案。所以我試著說 if [ -f *.txt ] 但它一直給我同樣的錯誤。但是,當我對腳本使用相同型別的格式來判斷是否存在以 .cpp 結尾的檔案時,我只是使用了與 if [ -f *.cpp ] 相同的格式并且它可以作業。我已經嘗試使用引號以及我檢查是否存在以 .j??pg 結尾的檔案并且我使用 if [ -e *."jpg" ] 來使其作業的部分,我嘗試了它txt 但還是不行。
if [ -f *.txt ]
then
for file in *.txt
do
echo moving $file ...
mv $file text
filesMoved=$((filesMoved 1))
done
fi
uj5u.com熱心網友回復:
在單括號條件中,所有的外殼擴展都會發生,特別是在這種情況下檔案名擴展。
condional 構造作用于它給出的引數的數量:-f期望只有一個引數跟隨它,一個檔案名。顯然您的*.txt 模式匹配多個檔案。
如果你的 shell 是 bash,你可以這樣做
files=(*.txt)
if (( ${#files[@]} > 0 )); then ...
或者,更便攜:
count=0
for file in *.txt; do
count=1
break
done
if [ "$count" -eq 0 ]; then
echo "no *.txt files"
else
echo "at least one *.txt file"
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462307.html
