脚本交互性:键盘输入与循环控制
1. 键盘输入交互性的引入
在编写脚本时,很多时候我们希望程序能够与用户进行交互,接收用户的输入。在此之前,我们编写的脚本大多缺乏这种交互性。例如之前的整数评估脚本:
#!/bin/bash
# test-integer2: evaluate the value of an integer.
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
if [ "$INT" -eq 0 ]; then
echo "INT is zero."
else
if [ "$INT" -lt 0 ]; then
echo "INT is negative."
else
echo "INT is positive."
fi
if [ $((INT % 2)) -eq 0 ]; then
echo "INT is even."
else
echo "INT is odd."
fi
fi
else
echo "INT is not an integer." >&2
exit 1
fi
每次想要改变 INT 的值时,都需要编辑脚本。如果脚本能够直接向用户询问值,会更加实用。
2. read 命令读取标准输入
read </
超级会员免费看
订阅专栏 解锁全文
786

被折叠的 条评论
为什么被折叠?



