4

Can I use read to capture the \n \012 or newline character?

Define test function:

f() { read -rd '' -n1 -p "Enter a character: " char &&
      printf "\nYou entered: %q\n" "$char"; }

Run the function, press Enter:

$ f;
Enter a character: 

You entered: ''

Hmmm. It's a null string.

How do I get my expected output:

$ f;
Enter a character:

You entered: $'\012'
$ 

I want the same method to be able to capture ^D or \004.

If read can't do it, what is the work around?

  • To do this in POSIX sh, see here. – Tom Hale Aug 1 '17 at 15:27
  • 2
    You need to prefix the read into a variable with IFS= – meuh Aug 1 '17 at 16:19
2

read -n1 still reads one line, but up to one character.

So if you press enter, you get an empty line, so an empty string is stored in the variable.

To read 1 character, use -N instead:

read -N1 var
2

bash builtin read can do this:

read -rd $'\0' -p ... -n 1
printf '\nYou typed ASCII %02x\n' "'$REPLY"

(this piece of code won't work with multi-byte characters)

Notice how I didn't put what is read in variable char as you did. This is because doing so would remove the characters in IFS from char. With a standard IFS, you wouldn't be able to differentiate between space, tab and newline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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