如何基于checking_file.sh的echo结果触发邮件?mailing.sh仅读取不执行
解决方案
核心需求梳理
- 保证
mailing.sh为流程中的最后执行步骤 mailing.sh仅读取checking_file.sh的内容,不直接执行该脚本- 根据
checking_file.sh中定义的判断逻辑结果触发邮件
具体实现步骤
1. 修改mailing.sh,实现读取脚本内容而非执行
我们从checking_file.sh中提取目标文件路径,然后在mailing.sh内自行完成文件存在性判断,避免直接执行原脚本:
#!/bin/bash # 读取checking_file.sh的内容,提取filepath变量的值 filepath=$(grep -E '^filepath=' /home/documents/checking_file.sh | cut -d'=' -f2 | tr -d '"') # 复制checking_file.sh中的判断逻辑 if [ -f "$filepath" ]; then echo "file is available in time no mail needed" else echo "trigger mail to developer" # 可在此添加实际发邮件命令,例如: # mail -s "File Missing Alert" developer@example.com <<< "The file $filepath does not exist." fi
2. 确保mailing.sh最后执行
方式一:用主脚本控制执行顺序
编写主脚本run_all.sh,先完成所有前置操作,最后调用mailing.sh:
#!/bin/bash # 执行所有前置任务(如有需要,在此添加其他预执行操作) # echo "Running pre-tasks..." # 最后执行mailing.sh /home/documents/mailing.sh
给主脚本添加执行权限:
chmod u+x /home/documents/run_all.sh
之后仅需执行run_all.sh,即可保证mailing.sh为最后运行的脚本。
方式二:定时任务控制(定时执行场景)
如果使用cron定时执行,确保mailing.sh的执行时间晚于所有前置任务。例如:
# 前置任务每天凌晨2点执行 0 2 * * * /path/to/pre_task.sh # mailing.sh在凌晨2点10分执行,确保前置任务完成 10 2 * * * /home/documents/mailing.sh
关键说明
- 原
chmod u+r+X /home/documents/checking_file.sh仅保证脚本的可读/可执行权限,无法控制执行顺序,需通过主脚本或定时任务实现顺序控制。 - 修改后的
mailing.sh通过grep和cut提取目标路径,完全基于读取原脚本内容实现判断,未执行checking_file.sh。
内容的提问来源于stack exchange,提问作者rag
相关产品推荐
相关产品推荐

