Solved read -n

Hi,

I tried to use read -n to cleanly break out of a while loop (see code below).
Looks like FreeBSD doesn't like the -n option.

Any ideas?

Thanks!


> Options
> ...
> -n nchars return after reading NCHARS characters rather than waiting
> for a newline, but honor a delimiter if fewer than
> NCHARS characters are read before the delimiter


Code:
while true
do

aa=`sysctl hw.acpi.thermal.tz0.temperature | awk 'BEGIN{FS="[ C]"}{ print $2 } ' `

echo "$aa"

read -n 1  -r  -t 2  -p "Press Any Key to Quit" bbb

if [ ! -z $bbb ]
  break
fi
done
 
The implementation of read depends on the shell that you are using. This code will work, but when using /bin/sh the -n option is illegal:

Code:
#!/bin/sh

while true ; do
   read -t 2 bbb
    if [ ! -z $bbb ] && [ $bbb = "q" ] ; then
        break
    fi
    echo -n "."
done

You could try with another shell.
 
> Options
> ...
> -n nchars return after reading NCHARS characters rather than waiting
> for a newline, but honor a delimiter if fewer than
> NCHARS characters are read before the delimiter
read(1) is a shell builtin and this is from the bash(1) manual.
 
ksiu said:
So what is the equivalent of -n for Bourne shell?

I don't think /bin/sh has something like that. What you could do is use Bash instead, since you seem to have it installed:

Code:
#!/usr/local/bin/bash

while true
do
   read -n 1  -r  -t 2  -p "Press Any Key to Quit" bbb
   ...

Note line 1, that is where you choose the shell.
 
use stty -icanon then head -c 1
without stty the tty driver wont return its input anyway before CR is pressed
 
I don't think /bin/sh has something like that. What you could do is use Bash instead, since you seem to have it installed:

Code:
#!/usr/local/bin/bash

while true
do
   read -n 1  -r  -t 2  -p "Press Any Key to Quit" bbb
   ...

Note line 1, that is where you choose the shell.

I want to keep it in Bourne Shell...so I call Bash in one line (see line 10 below)...don't know if it is good programming practice or not...but it seems to work...

Code:
1  #!/bin/sh
2
3  while true
4  do
5
6  aa=`sysctl hw.acpi.thermal.tz0.temperature | awk 'BEGIN{FS="[ C]"}{ print $2 } ' `
7
8  echo -n "$aa  "
9
10  hhh=`/usr/local/bin/bash -c 'read -t 2 -p "press any key to quit" -n 1 ggg; echo $ggg'`
11  echo
12
13  if [ ! -z $hhh ]; then
14    echo "break"
15    break
16  fi
17
18  done
 
Back
Top