为什么命令“读”不起作用?

时间:2016-09-22 05:47:35

标签: bash

#!/bin/bash
while read user;
do
echo "Do you want to send the message to $user?"
read response
case $response in
Y|y) echo The message was sent;;
N|n) echo The message was not sent;;
Q|q) exit;;
esac
done < users

为什么这段代码不适用于Ubuntu?如果我运行下一个代码,它就会完成;

#!/bin/bash
while read user;
do
echo "Do you want to send the message to $user?"
done < users

1 个答案:

答案 0 :(得分:3)

您需要阅读终端的响应,因此请使用</dev/tty进行用户响应。或者更具体地说,/proc/$$/fd/0可用于从stdin获取输入。

#!/bin/bash
while read user;
do
echo "Do you want to send the message to $user?"
IFS="" read -r response  </dev/tty # OR < /proc/$$/fd/0
case $response in
Y|y) echo The message was sent;;
N|n) echo The message was not sent;;
Q|q) exit;;
esac
done < users