深入探索Bash脚本:条件判断、表达式与交互式输入
1. 脚本退出状态与函数返回值
在脚本编写中,确保操作符后始终跟随字符串是很重要的,即便字符串为空。脚本结尾附近常出现 exit
命令,它接受一个可选参数作为脚本的退出状态,若未传参,退出状态默认设为0。例如,当 $FILE
扩展为不存在的文件名时,使用 exit
可指示脚本执行失败。脚本最后一行的 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."
fi