外壳脚本 - 运行命令列表


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 脚本中止,并且. ./foo.txt从当前 shell 中的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

提到的代码。

for i in `cat foo.txt`
do
$i
done     

请使用 https://www.shellcheck.net/

This will result    _ 
$ shellcheck myscript
Line 1:
for i in `cat foo.txt`
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang.
^-- SC2013: To read lines rather than words, pipe/redirect to a 'while read'   loop.
^-- SC2006: Use $(...) notation instead of legacy backticked `...`.
Did you mean: (apply this, apply all SC2006)
for i in $(cat foo.txt)
$ 

将尝试同时循环,并出于测试目的 foo 的内容.txt如下所述

cat foo.txt
ls -l /tmp/test
ABC
pwd

while read -r line; do $line; if [ "$?" -ne 0 ]; then echo "Send email Notification stating  $line Command reported error "; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating  ABC Command reported error
/tmp

如果报告错误,您可以中断循环。 http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_05.html

while read -r line; do $line; if [ "$?" -ne 0 ]; then echo "Send email Notification  stating  $line Command reported error "; break; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating  ABC Command reported error


while read -r line; do eval $line; if [ "$?" -ne 0 ]; then echo "Send email Notification stating  $line Command reported error "; break; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating  ABC Command reported error

最新更新