POSIX 替代 bash 读取超时和字符限制 [英] POSIX alternative to bash read with timeout and character limit

查看:56
本文介绍了POSIX 替代 bash 读取超时和字符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要在尽可能多的系统上运行的交互式 shell 脚本.是否有替代方法来实现与标准 POSIX 系统兼容的以下内容?

I am writing an interactive shell script that needs to run on as many systems as possible. Is there an alternative way to implement the following that is compatible with a standard POSIX system?

#! /bin/bash
echo -n "Do you wish to continue? (Y/n) 5 seconds to respond... "
read -n 1 -t 5 answer # accepts a single character, 5 second timeout.
if [ "$answer" = "n" ] || [ "$answer" = "N" ] ; then
  echo -e "\nExiting..."
  exit
fi
echo -e "\nContinuing with script..."
# More code

read 的超时对我来说是最重要的(read -t 5).读取的一个字符限制是可取的,但不是必需的(read -n 1).理想情况下,该脚本可以在 POSIX 系统和 bash 中运行,而无需启用特殊的 POSIX 兼容模式.

The timeout on read is most important to me (read -t 5). The one character limit for read is desirable but not essential (read -n 1). Ideally, the script would work on POSIX systems and also within bash without having to enable a special POSIX compatibility mode.

推荐答案

根据 Dickey 先生的回答调整 stty 设置,如果按下 'n' 或 'N' 以外的任何内容,以下内容似乎可以工作并继续执行脚本.

Adapting the stty settings from Mr Dickey's answer, the following seems to work and continues with the script if anything other than 'n' or 'N' is pressed.

据我所知,所有 stty 设置都是 posix.

As far as I can tell, all of the stty settings are posix.

#!/bin/sh

read_char() {
        old=$(stty -g)
        stty raw -echo min 0 time 50
        eval "$1=\$(dd bs=1 count=1 2>/dev/null)"
        stty $old
}

printf "Do you wish to continue? (Y/n) 5 seconds to respond..."
read_char answer
# answer=$(getch)
# answer=$(getche)

if [ "$answer" = "n" ] || [ "$answer" = "N" ] ; then
  printf "\nExiting...\n"
  exit
fi

printf "\nContinuing with script...\n"

read_char"的替代方案:

这样可以避免使用 eval(可能不安全)

This avoids using eval (can be unsafe)

getch() {
        old=$(stty -g)
        stty raw -echo min 0 time 50
        printf '%s' $(dd bs=1 count=1 2>/dev/null)
        stty $old
}

这避免了 eval 并打印按下的键

This avoids eval and prints the pressed key

getche() {
        old=$(stty -g)
        stty raw min 0 time 50
        printf '%s' $(dd bs=1 count=1 2>/dev/null)
        stty $old
}

这篇关于POSIX 替代 bash 读取超时和字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆