使用 cron 调度时如何在 shell 脚本中 grep 命令的输出

How to grep the output of a command inside a shell script when scheduling using cron

我有一个简单的 shell 脚本,我需要在其中检查我的 EMR 作业是否 运行,我只是在打印日志,但在安排使用 cron 的脚本,因为它总是打印 if 块语句,因为“status_live”var 的值始终为空,所以如果有人可以在这里提出错误建议,否则在手动 运行 脚本上它可以正常工作。

#!/bin/sh

status_live=$(yarn application -list | grep -i "Streaming App")

if [ -z $status_live ] 
then
  echo "Running spark streaming job again at: "$(date) &
else
  echo "Spark Streaming job is running, at: "$(date)
fi
# $? will have the last command status in bash shell scripting
# your complete command here below and status_live is 0  if it finds in grep (i.e. true in shell if condition.)
yarn application -list | grep -i "Streaming App"
status_live=$?
echo status_live: ${status_live}
if [ "$status_live" -eq 0 ]; then
    echo "success
else
    echo "fail" 
fi

您的脚本不能在 cron 中 运行 因为 cron 脚本根本没有环境上下文。

例如,尝试 运行 您的脚本作为没有 shell.

的另一个用途 nobody
 sudo -u nobody <script-full-path>

它将失败,因为它没有环境上下文。

解决方案是将用户环境上下文添加到脚本中。只需将 source 添加到您的 .bash_profile

 sed -i "2a source $HOME/.bash_profile" <script-full-path>

您的脚本应如下所示:

#!/bin/sh
source /home/<your user name>/.bash_profile

status_live=$(yarn application -list | grep -i "Streaming App")

if [ -z $status_live ] 
then
  echo "Running spark streaming job again at: "$(date) &
else
  echo "Spark Streaming job is running, at: "$(date)
fi

现在尝试与用户 nobody 再次 运行 它,如果它有效,那么 cron 也会起作用。

 sudo -u nobody <script-full-path>

请注意 cron 没有标准输出。并且您需要将脚本的标准输出重定向到日志文件。

<script-full-path> >> <logfile-full-path>