提升脚本交互性:键盘输入读取与循环控制全解析
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的值,都需编辑脚本。若脚本能向用户询问值会更有用,接下来将探讨如何为程序添加交互性。