如何在读取文件的循环内提示用户从 shell 脚本(ksh)输入?
脚本读取一个文件。每次循环都会询问用户是否要取消?该函数在循环外运行良好。在循环内,变量将填充文件的行。脚本不会因交互而停止。
有任何想法吗?
剧本:
######################################################
func_yesno(){
echo "cancel y/n?"
read answer
echo Your answer: $answer
case $answer in
y*|Y*) exit 0 ;;
n*|N*) echo ok ;;
*) echo wrong! ;;
esac
}
func_yesno
while read line
do
echo line: $line
func_yesno
done < /tmp/in.txt
func_yesno
######################################################
输入文件in.txt:
Koeln
Aachen
Muenchen
Hamburg
Berlin
输出:
# /tmp/a.sh
cancel y/n?
n
Your answer: n
ok
line: Koeln
cancel y/n?
Your answer: Aachen
wrong!
line: Muenchen
cancel y/n?
Your answer: Hamburg
wrong!
line: Berlin
cancel y/n?
Your answer:
wrong!
cancel y/n?
n
Your answer: n
ok
答案1
函数的read
命令使用与 while 循环相同的 stdin read
。使用不同的文件描述符。此外,该函数可以更简单:
func_yesno() {
typeset answer PS3="Cancel (y/n)?"
select answer in Yes No; do
case $answer in
Yes) exit 0 ;;
No) echo "ok"; break ;;
esac
done
}
while read -u3 line; do
echo "line: $line"
func_yesno
done 3< unique.txt