Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm writing a simple bash script, and as per my assignment specifications, it is to terminate on ctrl-d. However, it doesn't do that, it just stops reading the current input and begins reading the next input. How can I fix that? Here's my script:

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
share|improve this question
    
Control-D is only end of input. So you just signal that you finished one input and then continiue ina while true. If you ever want to break out of that loop then you can change that while true to a 'while (some_condition)' and change that condition in the loop. –  Hennes Jan 25 at 18:54
    
Ok that makes sense. But how can I sry an exit condition based on ctrl d because that's my requirement? –  OpenSrcFTW Jan 25 at 18:59

2 Answers 2

You can check the exit code from the read command.

if [[ $? != 0 ]]; then
    echo "Exiting"
    exit 1
fi
share|improve this answer
    
This would work but we aren't yet allowed to use while loops. –  OpenSrcFTW Jan 26 at 21:12
up vote 0 down vote accepted

Here's how I achieved the desired behavior:

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

Now when I press control-d the application exits just as desired.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.