I scheduled a cron job on a Mac to open Terminal every day at 11PM as follows:
0 23 * * * open -a Terminal
That works great! But what I would like is to not only open Terminal, but also to run a simple command within it. From looking online, it looks as if cron commands can be chained with &&
:
0 23 * * * open -a Terminal && echo 'Hello, world!'
However, this modified cron job only opens Terminal without running the second command there. Any thoughts on how I can get the cron job to do both?
Yes, using ; between the commands will guarantee that all commands are run sequentially, one after the other. The execution of one command would not depend on the exit status of the previous one.
* * * * * is a cron schedule expression wildcard, meaning your cron job should run every minute of every hour of every day of every month, each day of the week.
Multiple Commands in the Same Cron JobWe can run several commands in the same cron job by separating them with a semi-colon ( ; ). If the running commands depend on each other, we can use double ampersand (&&) between them. As a result, the second command will not run if the first one fails.
The tasks listed in cron will run in parallel, just as processes usually do. Theres no way of being sure which will start first, and no way in cron to make sure task A has complete before task B starts.
Great answers already provided by pah and Sameer Naik, but I ended up going with an even simpler solution using AppleScripts, inspired by an SO answer to a similar question.
0 23 * * * osascript -e 'tell application "Terminal" to do script "echo \"Hello, world\"!"'
You can create a script say my_cron_job.sh and execute it via cron
0 23 * * * my_cron_job.sh
Specify absolute path to the script e.g. /users/your_user_name/scripts/my_cron_job.sh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With