Shell脚本条件判断、表达式及交互式输入的深入解析
1. 脚本退出状态与函数返回值
在脚本中,exit命令可用于设置脚本的退出状态。当$FILE扩展为不存在的文件名时,使用exit能让脚本表明执行失败。若不传递参数,exit的退出状态默认值为 0。示例如下:
if [ ! -e "$FILE" ]; then echo "$FILE does not exist" exit 1 fi而对于 shell 函数,可通过return命令返回退出状态。例如将一个脚本转换为函数时,可用return替代exit:
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