linux - 在 Bash 脚本中测试用户是否可以使用 `read` 或等效方法输入数据
问题描述
我想知道用户是否可以输入数据。
在脚本中,通常可以调用read -r VARIABLE
以请求用户输入。但是,这并不适用于所有环境:例如,在 CI 脚本中,用户不可能输入任何内容,在这种情况下我想替换一个默认值。
到目前为止,我正在处理这个超时,如下所示:
echo "If you are a human, type 'ENTER' now. Otherwise, automatic installation will start in 10 seconds..."
read -t 10 -r _user_choice || _user_choice="no-user-here"
但老实说,这看起来很丑陋。
该解决方案不必使用read
,但它需要可移植到所有具有 Bash 的主要发行版,因此无法使用默认情况下未安装的软件包。
解决方案
$ cat stdin.bash
if [[ -t 0 ]]; then
echo "stdin is a terminal, so the user can input data"
else
echo "stdin is connected to some other redirect or pipeline"
fi
并且,展示
$ bash stdin.bash
stdin is a terminal, so the user can input data
$ echo foo | bash stdin.bash
stdin is connected to some other redirect or pipeline
从help test
输出:
-t FD True if FD is opened on a terminal.
推荐阅读
- express - 在快速应用程序中使用压缩中间件不起作用
- r - 在 ggplot 中绘制具有聚集标准误差的回归的置信区间
- xcode - 转换为 swift 4:找不到构建输入文件 target:Tests/_5__2Tests.swift'
- c# - 是否有与 Java 的 :: 表示法等价的指代成员函数?
- interface - 仅在 localhost 接口上使 socat 开放端口
- nvidia - 同时为 GPGPU 运行 NVIDIA,为图形运行 Intel
- angular - 离子:Firebase 查询返回丢失的数据
- javascript - 如何在点击时在 React 中打开单个弹出窗口并将道具传递给它
- c# - 距离未知日期时间的分钟数
- vb.net - 具有 Winforms / bindingsource 的实体 - 无法保存来自控件的用户输入