我很難弄清楚為什么我的腳本會創建檔案,但沒有將文本添加到它在“eggs”目錄中創建的檔案中。誰能幫我弄清楚我的代碼有什么問題?或者提供建議?我試過單 > 和雙 >> 附加到檔案的文本,但它沒有。它只是將檔案留空。
編輯:
file=0
RandomEgg=$(( RANDOM % 10 ))
cd eggs
while [ $file -lt 10 ]
do
touch "egg$file"
file=$(( file 1 ))
done
for files in $(ls eggs)
do
if [ $file -eq $RandomEgg ]
then
echo 'Found it!' > egg$file
else
echo 'Not Here!' > egg$file
fi
done
uj5u.com熱心網友回復:
在 bash 中,腳本可以簡化為
cd eggs || exit
RandomEgg=$(( RANDOM % 10 ))
for ((i = 0; i < 10; i)); do
if ((i == RandomEgg)); then
echo 'Found it!'
else
echo 'Not Here!'
fi > egg$i
done
或者,
cd eggs || exit
RandomEgg=$(( RANDOM % 10 ))
msg=('Not Here!' 'Found it!')
for ((i = 0; i < 10; i)); do echo "${msg[i == RandomEgg]}" > egg$i; done
uj5u.com熱心網友回復:
將第二個回圈更改為:
for files in egg*
do
if [ $files = "egg$RandomEgg" ]
then
echo 'Found it!' > $files
else
echo 'Not Here!' > $files
fi
done
您不需要使用ls來列出檔案,只需使用通配符即可。您還列出了錯誤的目錄——檔案是在當前目錄中創建的,而不是在eggs子目錄中。
您需要使用$files作為檔案名,而不是egg$file,因為這是此for回圈中的變數。
您必須使用=來比較字串,而不是-eq. -eq是數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362614.html
