Bash script returns different value when run from

2019-08-03 12:57发布

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?

4条回答
手持菜刀,她持情操
2楼-- · 2019-08-03 13:29

I lost a lot of time with this, and it was just missing at the beginning of the shell script file: #!/bin/bash

查看更多
Explosion°爆炸
3楼-- · 2019-08-03 13:38

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-08-03 13:42

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, not scriptname directly, which means the shebang is ignored. Why do you do so? Isn't the script marked executable?

查看更多
甜甜的少女心
5楼-- · 2019-08-03 13:47

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 in POSIX mode. I suspect that's not intended here.

查看更多
登录 后发表回答