Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

The following would do:

while read -r LINE ; do
  echo "$LINE" >> texttest.txt
done
  1. you don't need to touch the file first
  2. you don't need to initialize the LINE variable
  3. Ctrl+D closes stdin, which makes read exit with non-null (false) exit code
share|improve this answer
    
whoever edited my answer, I disagree. –  artm Oct 13 '14 at 6:36

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.