当作为cron作业运行时,Bash脚本不同的输出

时间:2014-06-13 02:33:23

标签: bash cron cron-task

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

当我手动运行时,返回“OK ...”当我将其作为cronjob运行时,它返回“警告......”

#!/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是相同的字符串/地址。

1 个答案:

答案 0 :(得分:0)

正如@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

为什么,我不知道...