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
This script is run from cron with the following entry:
0 * * * * sh /Users/username/path/wordcount.sh
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?
I lost a lot of time with this, and it was just missing at the beginning of the shell script file:
#!/bin/bash
When you run
sh ./wordcount.sh
which user is running the script?I suspect that the user that is executing cron won't be the same, so it's home (
~
) directory is different.I'd change any reference to
~
in your script to absolute directory paths.Agreeing with beny23 here, the most common error in cron script sources from the fact, that cron doesn't inherit your PATH. You have to set a cronpath inside the crontab, or use absolute paths.
A second error source might be, that it gets run from a differnt user.
A third one, that you call
sh scriptname
, notscriptname
directly, which means the shebang is ignored. Why do you do so? Isn't the script marked executable?Try to add
source ~/.bashrc
after the shebang, and another important thing :
don't call the script with
sh
if it's bash !With
sh
, bash is inPOSIX
mode. I suspect that's not intended here.