Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch CTRL +D in ksh

Tags:

linux

shell

ksh

How can I catch the CTRL+D keyboard in ksh and after exit?

while true; do
  read cmd
  echo $cmd
  if [ "$cmd" = "?????" ]; then
        break
  fi

done
like image 687
Marco Rocci Avatar asked Jul 25 '26 14:07

Marco Rocci


1 Answers

CTRL-D is "end-of-file (EOF)" and what you need to do is "trap" that input. Unfortunately, there isn't a EOF character -- when you hit the chord CTRL-D, the tty sends a signal to the reading application that the input stream has finished by returning a sentinel value to make it exit.

To prevent this character from being treated as further input, it has to be an special character (e.g. something out of range like -1). When the terminal detects such a character, it buffers all its characters so that the input is empty, which in turn makes your program read zero bytes (end of file).

You may be running into an issue because the read command exits when receiving eof, so your script was likely terminating before getting to your conditional. This has the side effect of breaking out of the script, but likely not in the way you wanted.

Try:

#!/usr/bin/env ksh

# unmap so we can control the behavior
stty eof ^D

while true; do
  read cmd
  echo $cmd

  # are we out of input? let's get a taco
  if [ ! -n "$cmd" ]; then
    echo 'taco time'
  fi

done

When you get to other signals (like ^C) the general form is:

trap [commands] [signals to catch]