如何将read-while循环转换为选择菜单



在我的Bash脚本中有以下read-while循环,它可以从用户处获取1-4之间的数字作为选项,并继续使用警告和"default"选项无效。然而,我最近遇到了内置的select,并觉得将我的read-while循环转换成一个可以大大简化我的脚本。问题是我不确定如何将read -n1select结合使用,这样用户输入的第一个1字符就会自动处理,而无需按enter键。

完成我在这里要做的事情的最好方法是什么?

我也意识到循环中还有其他冗余,我还没有能够修复,所以我欢迎在这方面的任何改进或优化。

wmstream1="[2:v]lut=a=val*0.7,fade=in:st=5:d=2:alpha=1,fade=out:st=$length1:d=2:alpha=1[v2];"
wmstream2="[v2][tmp2]scale2ref=w=oh*mdar:h=ih*0.1[wm_scaled][video];"
read -n1 -p "Select watermark position:
1) Top right
2) Top left
3) Bottom left
4) None
" ans  
while true; do 
case $ans in
1)  echo
echo "WARNING: defaulting to top-right position."
wmstream3="[video][wm_scaled]overlay=$wmpos:format=auto:shortest=1[outv];"
break               
;;
2)  echo
echo "Positioning watermark at top left."
wmpos="50:50"
wmstream3="[video][wm_scaled]overlay=$wmpos:format=auto:shortest=1[outv];"
break
;;
3)  echo
echo "Positioning watermark at bottom left."
wmpos="50:H-h-50"
wmstream3="[video][wm_scaled]overlay=$wmpos:format=auto:shortest=1[outv];"
break
;;
4)  echo
echo "Disabling watermark."
unset wmstream1
unset wmstream2
wmstream3="[tmp2]setsar=1[outv];"
break
;;
*)  echo 
echo "Invalid option selected. Select a valid number."
break
;;
esac
done

select可以代替while循环:

...
select ans in "Top Right" "Top Left" "Bottom Left" None
do
case $ans in
"Top Right") <Your code here>
"Top Left")  <your code here>
"Bottom Left") <Your code here>
None) <your code here>
esac
done

你不必像@Cyrus在评论中指出的那样使用那么多的回声。你可以在前面放一个回声select语句后的case块。

同样,while循环在你的代码中并不是真正需要的(如果这就是它的全部),因为你只提示用户输入一次,也只有一次。

编辑:Elect接受用户输入,因此它也可以替代read。除非你想同时使用两者来接受两个输入(这在代码中并不明显),否则这里的select将取代read(即,如果你想使用select)。