Bash Script using read needs to stop executing on Ctrl+D Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Bash Script using read needs to stop executing on Ctrl+D without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to write a script that will add a line to a text file if Enter is pressed.

But, if Ctrl+D is pressed, I need to exit that loop in the bash.

touch texttest.txt
LINE="0"
while true; do
    read LINE;
    if [ "$LINE" == "^D" ]; then
            break
    else
            echo "$LINE" >> texttest.txt
    fi
done

Currently have something like this but cannot figure out how I am do exit the while loop when Ctrl+D is pressed instead of Enter.

Answer

You’re overthinking it. All you need is this:

cat > texttest.txt

Cat will read from STDIN if you’ve not told it different. Since it’s reading from STDIN, it will react to the control character Ctrl+D without your having to specify it. And since Ctrl+D is the only thing that will finish the cat subprocess, you don’t even need to wrap it in a loop.

We are here to answer your question about Bash Script using read needs to stop executing on Ctrl+D - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji