
我正在編寫一個簡單的 bash 腳本,根據我的作業規範,它將在 ctrl-d 上終止。然而,它並沒有這樣做,它只是停止讀取當前輸入並開始讀取下一個輸入。我該如何解決這個問題?這是我的腳本:
while true ; do
echo Please enter your full name:
read fullName
echo Please enter your street addres:
read streetAddress
echo Please enter your zip code, city, and state in that order:
read zip city state
echo $fullName > Name.txt
echo "$streetAddress $city $state $zip" >> Locations.txt
echo $fullName >> "$zip".txt
echo $streetAddress >> "$zip".txt
echo "$city $state $zip" >> "$zip".txt
echo '' >> "$zip".txt
done
答案1
您可以從命令中檢查退出代碼read
。
if [[ $? != 0 ]]; then
echo "Exiting"
exit 1
fi
答案2
以下是我如何實現所需的行為:
notFinished=true
while $notFinished ; do
echo Please enter your full name:
while read fullName ; do
echo Please enter your street addres:
read streetAddress
echo Please enter your zip code, city, and state in that order:
read zip city state
echo $fullName > Name.txt
echo "$streetAddress $city $state $zip" >> Locations.txt
echo $fullName >> "$zip".txt
echo $streetAddress >> "$zip".txt
echo "$city $state $zip" >> "$zip".txt
echo '' >> "$zip".txt
continue 2
done
notFinished=false
done
現在,當我按下 control-d 時,應用程式將按預期退出。