脚本编程中的条件判断、输入读取与逻辑控制
1. 脚本退出状态与函数返回值
在脚本中,exit命令用于设置脚本的退出状态。它接受一个可选的整数参数,若未传递参数,退出状态默认值为 0。例如,当脚本中$FILE扩展为不存在的文件名时,使用exit可表明脚本执行失败。示例如下:
if [ ! -e "$FILE" ]; then echo "$FILE does not exist" exit 1 fi对于 shell 函数,可通过return命令返回退出状态。如将一个脚本转换为 shell 函数时,可把exit命令替换为return语句:
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