Shell脚本编程:条件判断、整数运算与用户交互
1. 脚本退出状态与函数返回值
在脚本编写中,确保操作符后总是跟有字符串是很重要的,即便字符串为空。脚本结尾处常出现的exit命令可接受一个可选参数,该参数将作为脚本的退出状态。若未传递参数,退出状态默认值为0。借助exit,当$FILE的值为不存在的文件名时,脚本就能指示失败。脚本最后一行的exit命令更多是一种形式,因为脚本运行到末尾(到达文件结尾)时,默认退出状态就是0。
同样,shell函数可通过在return命令中包含整数参数来返回退出状态。以下是将脚本转换为shell函数的示例:
test_file () { # test-file: Evaluate the status of a file FILE=~/.bashrc if [ -e "$FILE" ]; then if [ -f "$FILE" ]; then echo "$FILE is a regular file." fi if [ -d "$FILE" ]; then echo "$FILE is a directory." fi if [ -r "$FILE" ]; then echo "$FILE is readable."