Bash 脚本不会在 ctrl d 上退出

Bash 脚本不会在 ctrl d 上退出

我正在编写一个简单的 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 时,应用程序就会按预期退出。

相关内容