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

1
  • Consider running your code through shellcheck.net and fixing what it finds. (I'd also suggest making sure you can answer the exercises below the allegory in BashFAQ #105 before using set -e -- its behavior is subtle, oft-confusing, and can easily cause more bugs than it avoids). Commented Apr 20, 2018 at 15:48

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.