0

the script is:

#!/bin/bash

SCRIPTLOG=~/tmp/logfile
[ ! -d ~/tmp ] && mkdir ~/tmp

while getopts ":u:g:y" options; do
  case $options in
    u )
     user=$OPTARG;;
    g )
     group=$OPTARG;;
    * )
     echo "wrong option: ${OPTARG}"
     exit 1;;
  esac
done

set -e

add_etx_members ()
{

user="${1}"
group="${2}"

set -u
echo "Users to add to ${group}:"
echo
echo "--- BEGIN ---"
printf "%-10s\n" $user
echo "--- END ---"
echo

while true; do
    read -r -p "Continue? [y/n]: " REPLY
    case $REPLY in
      [yY]) echo;break ;;
      [nNqQ]) echo;exit ;;
      *) printf "\033[31m%s\033[0m\n" " invalid input: ${REPLY}"
    esac
done

echo "here commands"

}

add_etx_members "${user}" "${group}" 2>&1 | tee -a ${SCRIPTLOG}

when I run single execution from command line it works (reaches "echo here commands"):

$ myscpt1 -u test -g ABC
Users to add to ABC:

--- BEGIN ---
test
--- END ---

Continue? [y/n]: y

here commands
$

but when I run it in while loop, it fails:

$ echo -e "ABC\nSDE"|while read a;do myscpt1 -u test -g ${a};done
Users to add to ABC:

--- BEGIN ---
test
--- END ---

 invalid input: SDE
$

Although, the commands are the same as from single run:

$ echo -e "ABC\nSDE"|while read a;do echo myscpt1 -u test -g ${a};done

myscpt1 -u test -g ABC

myscpt1 -u test -g SDE

Chris
  • 939
  • 2
  • 11
  • 22
  • Consider running your code through http://shellcheck.net/ and fixing what it finds. (I'd also suggest making sure you can answer the exercises below the allegory in [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105) before using `set -e` -- its behavior is subtle, oft-confusing, and can easily cause more bugs than it avoids). – Charles Duffy Apr 20 '18 at 15:48

1 Answers1

1

because the read inside the script is consuming the same input (the standard input is inherited from caller) as the while read calling the script.

may be resolved redirecting input inside script

exec < /dev/tty

or just for the while read

while ...;
done < /dev/tty

Note that while true could be changed by while read

or from outside depending on what you need

echo -e "ABC\nSDE"|while read a;do myscpt1 -u test -g ${a} < /dev/null;done
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36