Wednesday, May 15, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 865  / 2 Years ago, wed, july 13, 2022, 9:04:35

I have a read_user_input.sh script:


#!/bin/bash

# set -e

prompt="bla? [Y/n] "

while true; do
read -p "$prompt" -n 1 -s -t 3 reply
case $reply in
""|Y|y) echo "bla!!!"; break;;
N|n) echo "no bla :( you suck"; break;;
*) ;;
esac
done

Works as I expected - i.e.



  • User inputs "Y" -> bla

  • User inputs "y" -> bla

  • User hits Enter -> bla

  • Timeout -> bla


However, when adding set -e - the read ends with error > 128.


From read --help:



Exit Status:


The return code is zero, unless end-of-file is encountered, read times out
(in which case it's greater than 128), a variable assignment error occurs,
or an invalid file descriptor is supplied as the argument to -u.




What would be the best way to overcome this?



  1. adding || true seems not right, as it would hide any real errors.

  2. I also don't want to remove the set -e.

  3. One other thing I thought about was handling it in trap but that seems like an overkill


More From » command-line

 Answers
0

Instead of adding || true, set the $reply to y if there was a timeout:


    read -p "$prompt" -n 1 -s -t 3 reply || {
err=$?
if (( $err > 128 )) ; then
reply=y
else
exit $err
fi
}

[#796] Wednesday, July 13, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
algicuade

Total Points: 317
Total Questions: 89
Total Answers: 106

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;