0

For my purpose, I need to execute a shell command, achieve the output, and for each line ask user for prompt. The problem is that on the read prompt, stdin buffer isn't empty

this is my code:

#!/bin/sh

git branch -a | sed 's/remotes\/origin\///g'

echo "############################"

git branch -a | sed 's/remotes\/origin\///g' | while read line
do
        if [[ "$line" != *develop* ]] \
                && [[ "$line" != *master ]] \
                && [[ "$line" != *release/* ]] \
                && [[ "$line" != *hotfix* ]]
        then
                read -r -p "Do you want to delete branch $line <y/N>?" prompt
                echo $prompt
        fi
done

The line:

read -r -p "Do you want to delete branch $line <y/N>?" prompt

does not even display to video, and prompt variable show the result of line variable above. How can I solve this problem?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Fabrizio Stellato
  • 1,727
  • 21
  • 52

1 Answers1

1

Use a FD other than 0 (stdin), to leave the original stdin free for input from the user:

#!/usr/bin/env bash
#              ^^^^- NOT /bin/sh; also, do not run with "sh scriptname"

while read -r line <&3; do
  line=${line#remotes/origin/}  # trim remotes/origin/ w/o needing sed
  case $line in
    *develop*|*master|*release/*|*hotfix*) continue ;;
    *) read -r -p "Do you want to delete branch $line <y/N>?" prompt
       echo "$prompt" ;;
  esac
done 3< <(git branch -a)

Here, we're using FD 3 for output from git, such that FD 0 is still stdin, available to read from the user; and then redirecting <&3 on the explicit read where we want content from git.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441