Can Bash recognize when it's being asked for input?

Let's say I want to run

git ls-remote "https://github.com/OrgName/RepoName.git" branchname

in a script to "ping" GitHub for the existence of a branch branchname in the indicated repository.

There are two possible responses from GitHub:

  1. If branchname exists, the command completes with an exit code and GitHub returns some information about it that I can parse.

  2. If branchname doesn't exist, GitHub will respond by asking for my username, and the script will hang at the prompt

Username for 'https://github.com':

while waiting for input.

Is there any condition I can check within the script to distinguish between these two cases? That is, is there any condition that will tell me, "The command has not returned an exit code, but is instead waiting for user input" so that I can cut it off, consider the git ls-remote command a failure, and proceed with the script?

I've tried redirecting to /dev/null with

git ls-remote -h "https://github.com/OrgName/RepoName.git" &> /dev/null

but the script still hangs to prompt for my GitHub username.


is there any condition that will tell me, "The command has not returned an exit code, but is instead waiting for user input" so that I can cut it off […]?

Not without support from another tool. Bash is not between the terminal and the command. When the command is in the foreground, Bash is in the background waiting. It does not relay input nor output. The command (here: git) uses the terminal directly.

A tool designed to be between your terminal and whatever command is expect(1). With it you can react to a prompt in an automated way. It seems you don't need expect though. What you want to do can be done by configuring git.

You want to "consider the git ls-remote command a failure". See what man 1 git states about GIT_TERMINAL_PROMPT environment variable:

GIT_TERMINAL_PROMPT
If this environment variable is set to 0, git will not prompt on the terminal (e.g., when asking for HTTP authentication).

GIT_TERMINAL_PROMPT=0 git ls-remote "https://github.com/OrgName/RepoName.git" branchname

If not the variable, the above command would prompt me for username. Because of the variable it prints fatal: could not read Username for 'https://github.com': terminal prompts disabled. The message can be suppressed by 2>/dev/null. The exit status is 128.

Note this solution does not make Bash recognize when git prompts, it does not make Bash "cut it off". git fails by itself and Bash moves on to the next command.

I believe with GIT_TERMINAL_PROMPT=0 you will be able to distinguish your two cases by examining the exit status of git.