简体   繁体   中英

Unix, how to put crontab in a shell script

I am new to Unix and not sure how to use crontab. I want to write a program that will update a file every midnight. 0 0 * * * (Midnight every day). I want the user to enter a value for in_variable(please look at the following code) only the first time when the program runs, and do the rest Every Midnight (without prompting the user to enter anymore values after the very first time). depending on the old input(in_variable), the program should execute the if else statement every midnight. Please let me know if this is possible? any help would be greatly appreciated.

echo "which message would you like to output: "
read in_variable
0 0 * * * 
if [ $in_variable -eq "1" ]; then
   echo "output message 1" >> file1
else
   echo "output message 2" >> file2
fi

Cron jobs are automatic and cannot rely on any human interaction.

Your script should read its initial input from a file or its initialisation must be done with an interactive script (not from cron ).

Also note that you don't specify the schedule in the shell script, but in the crontab itself. That is to say, your question is back-to-front . You should ask how to put a shell-script into a crontab ? For which the answer is essentially:

See man cron . (Linked resource is for BSD, your cron implementation may be different).

Make the script to ask which message to use separate of the cron job, putting the message in a file under /var/lib . Make the cron job check for presence of the file, and then handle appending the contents if present.

crontab doesn't work like that. You don't put the time specification in the program that you want to run; you put the time specification in a crontab file somewhere (where varies by system) which specifies both when to run the program and what program or command to run.

Ignacio has it right regarding what to do with the variable: store the variable in a file in a fixed location, then have your script check for the existence of the file. Cron will have nothing to do with that part.

A quick ugly hack (more about why it is a hack after) would be:

echo "which message would you like to output: "
read in_variable

if [ $in_variable -eq "1" ]; then
   echo '0 0 * * * echo "output message 1" >> file1' | crontab -
else
   echo '0 0 * * * echo "output message 2" >> file2' | crontab -
fi

This is ugly because it erases the current crontab entirely. A more sophisticated answer would provide some sort of 'tag' for the new line being added to the crontab, and overwrite the old line if someone runs the script a second time. It would also provide a mechanism to remove the line, all while maintaining the preexisting cron table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM