gpt4 book ai didi

linux - 如果发生 "read -t"超时,设置要使用的变量的默认值

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:57 25 4
gpt4 key购买 nike

我正在尝试读取设置了默认值的用户输入,但是当我执行回显时,数据未打印

#!/bin/sh
ROUTETOCOM="n"
read -t 4 -p "Route data from Port? [y/n] : " ROUTETOCOM
echo $ROUTETOCOM

如果用户在 4 秒内没有输入任何值 echo $ROUTETOCOM 不显示 'n'脚本有什么问题?

最佳答案

建议的解决方法

如果您想应用默认值,请在事后执行:

read -t 4 -p "Route data from Port? [y/n] : " route_toggle
: "${route_toggle:=n}"

另见 Bash-Hackers' Wiki page on parameter expansion -- 特别是关于 using a default value 的部分或 assigning a default value .


说明

read -t 的文档如下(对于 bash 3.2):

The -t option causes read to time out and return failure if a complete line of input is not read within TIMEOUT seconds. If the TMOUT variable is set, its value is the default timeout. The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u.

或者,对于 bash 4.3:

-t timeout - time out and return failure if a complete line of input is not read within TIMEOUT seconds. The value of the TMOUT variable is the default timeout. TIMEOUT may be a fractional number. If TIMEOUT is 0, read returns immediately, without trying to read any data, returning success only if input is available on the specified file descriptor. The exit status is greater than 128 if the timeout is exceeded

本文档的任一版本均未表达或暗示超时不会导致值更改; 唯一保证是在发生超时的情况下返回代码不会为零。


关于linux - 如果发生 "read -t"超时,设置要使用的变量的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com