1

I'd like to know if the user can input data.

In a script, it is usually possible to call read -r VARIABLE to request input from the user. However, this doesn't work in all environments: for example, in CI scripts, it's not possible for the user to input anything, and I'd like to substitute a default value in that case.

So far, I'm handling this with a timeout, like this:

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"

But honestly, that just looks ugly.

The solution doesn't have to use read, however it needs to be portable to all major distros that have Bash, so it's not possible to use packages that are not installed by default.

2
  • what is a CI script? Commented May 14, 2020 at 17:19
  • Continuous Integration, basically automated tests that run on another server; there's no user there so scripts cannot be interactive Commented May 15, 2020 at 18:08

1 Answer 1

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

and, demonstrating

$ 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

From help test output:

  -t FD          True if FD is opened on a terminal.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.