【问题标题】:Bash script different ouput when run as cronjob作为 cron 作业运行时的 Bash 脚本不同的输出
【发布时间】:2014-08-03 12:17:16
【问题描述】:

当我尝试将以下基本脚本作为 cronjob 运行时,它返回的结果与我手动运行时不同。

当我手动运行它时返回“OK...”当我将它作为 cronjob 运行时它返回“WARNING...”

#!/bin/bash
#
# This script will check the public IP address of your server and compare it against a recent check
# The purpose of this script is to notify you when your public IP address has changed for remote access purposes
#
# Start by defining a couple variables (One checks the last IP, one checks the current)
#
last_ip=$(more /tmp/last_ip_check.txt)
current_ip=$(curl -s ifconfig.me)
date=$(date)
#
#
if [ "$last_ip" == "$current_ip" ]
then
  echo "$date OK: Your IP address hasn't changed" >> /tmp/ip_address_changes
else
  echo "WARNING: Your IP address has changed to $current_ip" | mailx -s "Plex IP Address Change" emailaddress@domain.com
  echo "$date WARNING: Your IP address has changed to $current_ip" >> /tmp/ip_address_changes
fi
#
# Dump the output of your ip check into the /tmp file for the next check
#
echo "$current_ip" > /tmp/last_ip_check.txt
#

我已经获得了 bash_profile 的来源,并在没有运气的情况下向脚本添加了不同的路径。另请注意,last_ip 和 current_ip 是相同的字符串/地址。

【问题讨论】:

  • 你为什么在$(...)中使用寻呼机more而不是$(cat /tmp/last_ip_check.txt)
  • 尝试将set -x 放在脚本的开头,以便在执行时输出所有命令。然后检查您的电子邮件以获取输出。
  • 当您使用 cron 时,curl 很可能不在您的路径上。指定完整路径或在脚本中设置路径。

标签: bash cron cron-task


【解决方案1】:

正如@Barman 所说,如果您将more 更改为cat,它会起作用:

改变这一行:

last_ip=$(more /tmp/last_ip_check.txt)

到这里:

last_ip=$(cat /tmp/last_ip_check.txt)

... 并等待脚本的下一次执行。

我不知道原因,但由于more 是一个寻呼机,我相信cat 在这种情况下使用更正确

但是,如果我测试两个结果和diff 他们,我没有发现任何差异:

jim@debian:~$ cat /tmp/last_ip_check.txt
1xx.1xx.2xx.1xx
jim@debian:~$ more /tmp/last_ip_check.txt
1xx.1xx.2xx.1xx
jim@debian:~$ cat /tmp/last_ip_check.txt > a
jim@debian:~$ more /tmp/last_ip_check.txt > b
jim@debian:~$ diff a b

为什么会这样,我不知道...

【讨论】:

  • 感谢 jim 和 barmar 修复它。我完全隔开它并开始假设这是一个环境问题。谢谢你们的帮助。
  • 由于这是 bash,您可以节省一些宝贵的微秒时间并使用 last_ip=$(</tmp/last_ip_check.txt)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 2021-06-18
  • 2011-10-06
  • 1970-01-01
  • 2011-05-10
  • 2017-07-08
相关资源
最近更新 更多