深入探索Bash脚本:条件判断、输入读取与逻辑操作
1. 脚本退出状态与函数返回值
在Bash脚本中,exit命令可设置脚本的退出状态。当不带参数时,默认退出状态为 0;若$FILE扩展为不存在的文件名,可使用exit命令表明脚本执行失败。示例如下:
if [ ! -e "$FILE" ]; then exit 1 fi同样,shell 函数可通过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 if [ -r "$FILE" ]; then echo "$FILE is readable." fi if [ -w "$FILE" ];