首页 > 解决方案 > 在 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 的主要发行版,因此无法使用默认情况下未安装的软件包。

标签: linuxbash

解决方案


$ 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.

推荐阅读