在 Shell Script 读取输入时, 很多时需要按字串的长度作出不同的处理, 而 Shell Scrit 检查变量的字串长度十分简单, 写法如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/bin/sh ### 读入的变量 echo "Please input string: " read string if [ ${#string} -ge 10 ]; then echo "Error!"; exit fi echo "Done!" |
上面的程式码会检查用户输入的变量 “string”, 然后检查 string 变量的长度, 如果字串长度大过 10, 会显示 “Error!”, 并结束程式执行; 如果变量的字串长度等如或小于 10, 会继续执行。