【问题标题】:Output of SQL query and command to a file in shell script将 SQL 查询和命令输出到 shell 脚本中的文件
【发布时间】:2015-06-11 15:17:12
【问题描述】:

我有以下 shell 脚本,它运行一个 SQL 查询和一个将输出作为电子邮件发送的命令。问题是我只能发送 SQL 输出。不是 for 循环的输出。我试图在 for 循环之后给出“EOF”,但随后它给出了语法错误。请让我知道如何通过电子邮件发送这两个输出。

感谢和问候, 阿基尔

#!/bin/bash
source $HOME/.bash_profile

cd /home/cron

wfVAR="red blue green"


echo " " > /home/cron/output.lst
sqlplus -s user/test@DB <<EOF
set linesize 55 pages 500
spool output_temp.lst;
set head off;
select sysdate from dual;
set head on;
spool off;
EOF

for name in ${wfVAR}; do
  pmcmd getworkflowdetails -sv REPOSITORY ${name} | grep -e "Workflow:" -e "Workflow run status:" -e "End time:"
 done

sed -e 's/ *$//' output_temp.lst > output.lst
cat /home/cron/output.lst | mail -s "Output - `date '+%d-%m-%y'`" akhil@gmail.com
rm output_temp.lst

【问题讨论】:

  • 顺便说一句,很少需要cd 进入目录,并且使脚本依赖于调用用户的.bash_profile 通常根本不是一个好主意。和以往一样,cat file | mail 更好地表达mail &lt;file
  • 您没有创建output_temp.lst,也没有捕获来自sqlpluspmcmd 的输出。

标签: bash shell unix cron


【解决方案1】:

您正在覆盖文件。

echo moo >output.lst
echo bar >output.lst

现在,output.lst 仅包含 bar

诀窍是追加,而不是覆盖。

echo moo >output.lst
echo bar >> output.lst

您的脚本有多个额外的问题,因此不清楚您真正想要它做什么。我猜是这样的。

sql things >output.lst
for var in things; do stuff; done | sed 's/ *$//' >>output.lst

...巧合的是,如果您愿意,也可以通过在子shell中运行命令并重定向子shell的输出来完成单个重定向:

( sql things
  for var in things; do stuff; done | sed 's/ *$//' ) >output.lst

根据这些推测,您的整个脚本可能是

#!/bin/bash
# source $HOME/.bash_profile   ######## XXX probably don't do this

output=/home/cron/output.lst

sqlplus -s user/test@DB <<EOF >$output   # Capture output from SQL
set linesize 55 pages 500
spool output_temp.lst;
set head off;
select sysdate from dual;
set head on;
spool off;
EOF

for name in red blue green; do
  pmcmd getworkflowdetails -sv REPOSITORY "$name"
done |
grep -e "Workflow:" -e "Workflow run status:" -e "End time:" |
# XXX: could benefit from refactoring grep x | sed y to just sed '/x/!d;y'
sed -e 's/ *$//' >> $output
# XXX: fixed Useless Use of cat Award
mail -s "Output - `date '+%d-%m-%y'`" akhil@gmail.com <$output

如果您愿意,甚至可以避免永久输出文件;只需通过管道发送至mail

#!/bin/bash

( sqlplus -s user/test@DB <<__EOF
    set linesize 55 pages 500
    spool output_temp.lst;
    set head off;
    select sysdate from dual;
    set head on;
    spool off;
__EOF

  for name in red blue green; do
    pmcmd getworkflowdetails -sv REPOSITORY "$name"
  done |
  sed -e '/Workflow:\|Workflow run status:\|End time:/!d' -e 's/ *$//' ) |

mail -s "Output - `date '+%d-%m-%y'`" akhil@gmail.com

(...假设您的 sed 理解 \| 表示正则表达式中的交替)。

【讨论】:

  • 嗨 Tripleee,问题只是电子邮件中的 SQL 输出。我希望 for 循环的输出也在同一个文件中。
  • 答案就是这样做的,并解释了您的代码错误的原因。但是您发布的代码的行为与您描述的不完全一样。我们只能假设您发布的内容不完全是您正在运行的代码,或者您没有告诉我们一些细节(例如代码是否由 cron 作业运行,该作业会发送一封包含其标准的电子邮件输出和标准错误)。
  • 感谢 Triplee,它成功了。之前我还没有执行你写的代码。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-01-18
  • 2021-10-05
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
相关资源
最近更新 更多