带有while循环中参数的bash脚本

时间:2018-04-20 15:31:48

标签: bash shell

脚本是:

#!/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}

当我从命令行运行单个执行时它工作(到达“echo here命令”):

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

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

Continue? [y/n]: y

here commands
$

但是当我在while循环中运行它时,它失败了:

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

虽然命令与单次运行相同:

$ echo -e“ABC \ nSDE”|读取a时;执行echo myscpt1 -u test -g $ {a};完成

myscpt1 -u test -g ABC

myscpt1 -u test -g SDE

1 个答案:

答案 0 :(得分:1)

因为脚本中的读取正在使用相同的输入(标准输入继承自调用者),因为while读取调用脚本。

可以解决重定向脚本中的输入

exec < /dev/tty

或只是暂时阅读

while ...;
done < /dev/tty

请注意,while true

可以更改while read

或来自外部,取决于您的需求

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