Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

How to write a bc calculated variable to file using CRON jobs (linux, bash, script, cron)

I am a lot confused about this behavior.
Each time I run this script from terminal, it works fine, but it fails once is executed from a crontab.
Inside the script you can find each step description.
The target is to print date and time with the peso variable to a file.
I have changed line 16 countless times. Same thing for line #4.

Edit for clarity: THIS IS JUST A SMALL PART FROM THE WHOLE SCRIPT.
It runs nice every minute. It does everything, except the peso issue.

Please HELP!!!

1 # Here I compute one decimal value (like z=0.123) with two integers (sd and mean)
2 peso=$( echo "scale=4; ${z}*${sd}/100 + ${mean}/100" | bc -l) 
3 echo "peso_mtrx="$peso       # This is for checking: shows 40.123 (example), so it is OK
4 peso+=";"                    # Add a semicolon to check its behaviour
5 echo "peso= "$peso           # show it: OK
6 peso1=$(date "+%D %T")       # Now I capture date and time
7 echo "fecha= "$peso1         # shows it, so it is OK
8 peso1+=";"                   # add a semicolon to date
9 peso1+=$peso                 # concatenate the peso variable
10 echo $(printf '%s' "$peso1") # shows it, so it is ok up to here

11 echo $(printf '%s' "$peso1") >> ~/projects/Files/normal.csv           # WRITE TO FILE

12 # whenever I run this script from terminal, all variables showed right and even print all data into file.
13 # File stores a new line like:  02/03/21 08:24:40;40.1709; 

14 # BUT... when it is executed from a CRON job... everything except peso are stored.
15 # File stores a line like:  02/03/21 08:24:40;; peso variable just vanishes.

16 # is it something related to subshells? how to solve this rigmarole?
question from:https://stackoverflow.com/questions/66047838/how-to-write-a-bc-calculated-variable-to-file-using-cron-jobs-linux-bash-scri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I was suspicious, the whole thing was related to subshell issues.
I just did something inside crontab.
Once I execute crontab -e, I initially had something like:

*/1 * * * * /absolute/path/to/project.sh

So doing some reading I ended up doing this:

SHELL=/bin/bash
*/1 * * * * exec bash -l /absolute/path/to/project.sh

I beg to an expert to enlighten us about this solution. As far as I do understand, it is related to create a login shell inside cron using the information stored in .bash_profile.
It did enable the environment variables to be reachable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...