shell - shell 脚本 - 运行命令列表
问题描述
for i in `cat foo.txt`
do
$i
done
我有一个带有命令列表的输入文件“foo.txt”。
ls -ltr | tail
ps -ef | tail
mysql -e STATUS | grep "^Uptime"
当我运行shell脚本时,它会执行,但将每行中的命令分隔为空格,即第一行它只执行“ls”,然后是“-ltr”,我得到命令未找到错误。
如何将每个列表作为一个命令运行?
我为什么要这样做?
我执行了很多任意的 shell 命令,包括 DB 命令。当我执行每个命令(来自 foo.txt 的每一行)时,我需要进行错误处理,我想不出会出现什么问题,所以我的想法是将所有命令按顺序排列并在循环中调用它们并检查错误(#?) 在每一行并在出错时停止。
解决方案
为什么不这样做呢?
set -e
. ./foo.txt
set -e
如果命令以非零退出代码退出,则导致 shell 脚本中止,并从当前 shell 中. ./foo.txt
执行命令。foo.txt
但我想我无法发送通知(电子邮件)。
你当然可以。只需在子shell中运行脚本,然后响应结果代码:
#!/bin/sh
(
set -e
. ./foo.txt
)
if [ "$?" -ne 0 ]; then
echo "The world is on fire!" | mail -s 'Doom is upon us' you@youremail.com
fi
推荐阅读
- c# - 等待用户使用 Rg.Plugins.Popup 点击弹出窗口
- javascript - 使用 Google Apps 脚本将人员分组的最佳方法
- android - JUnit 5 - 参数化嵌套测试
- javascript - 如何在正则表达式中替换捕获组而不是完整匹配?
- amazon-web-services - 扩展 ECS 集群中的一些(但不是全部)任务
- amazon-s3 - 使用 fetch 调用具有自定义域和签名 cookie 的 Cloudfront S3 端点时出现 403 错误
- python - 在 Python 中获取客户端配置文件 Azure 的访问令牌
- reactjs - 推送状态而不重新触发组件加载
- android - 在其他小部件上颤动阴影
- asp.net - 我在 ionic 中使用 asp.net web api 服务。但它没有在真实设备中获取服务数据