首页 > 解决方案 > 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 的每一行)时,我需要进行错误处理,我想不出会出现什么问题,所以我的想法是将所有命令按顺序排列并在循环中调用它们并检查错误(#?) 在每一行并在出错时停止。

标签: shellautomation

解决方案


为什么不这样做呢?

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


推荐阅读