
簡単な 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 を押すと、アプリケーションは期待どおりに終了します。