从cron作业运行时,bash脚本返回的值与从命令行运行时返回的值不同 [英] Bash script returns different value when run from cron job than from command line
问题描述
我有一个bash脚本,旨在从cron运行。脚本会计算文档中的单词数,并将当前时间和单词数附加到CSV文件中。在相关部分中,脚本为:
I have a bash script that is intended to be run from cron. The script counts the words in document, and appends a line with the current time and the word count to a CSV file. In relevant part, the script is:
EPOCH=$(date +"%s")
WCC=$(wc -w ~/path/filename.txt | sed 's/\/Users\/username\/path\/filename.txt//' | sed 's/ //g')
echo $EPOCH,$WCCH4 >> ~/path/wordcount-data.csv
此脚本从cron运行,具有以下条目:
This script is run from cron with the following entry:
0 * * * * sh /Users/username/path/wordcount.sh
问题是 wc -w
从cron运行时返回的值与从cron运行时返回的值不同shell或从终端中执行的shell脚本运行时。换句话说,从cron执行的此脚本的值当前为12438,但在外壳程序中运行 wc -w filename.txt
或运行 sh。 /wordcount.sh
都返回12445的值。值得的是,差异始终为7,而vim的字数与cron运行的字数匹配。
The problem is that wc -w
returns a different value when run from cron than when run from the shell or when run from the shell script executed in the terminal. In other words, the value of this script executed from cron is currently 12438, but running wc -w filename.txt
in the shell or running sh ./wordcount.sh
both return values of 12445. For what it's worth the difference is always 7, and vim's word count matches the word count run from cron.
什么解释了不同的值,以及如何解决?
What accounts for the different values, and how do I fix it?
推荐答案
尝试添加
source〜/ .bashrc
重要的事情:
如果是bash,请不要使用 sh
调用脚本!
don't call the script with sh
if it's bash !
使用 sh
,bash处于 POSIX
模式。我怀疑这不是故意的。
With sh
, bash is in POSIX
mode. I suspect that's not intended here.
这篇关于从cron作业运行时,bash脚本返回的值与从命令行运行时返回的值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!