Score:0

run bash command inside a cron job in ubuntu

cn flag

I have a server running Ubuntu and I would like to create a cron job that runs every hour, the detail is that I want this cron to execute a bash command in a specific path, this would be an example of my command sudo bash/path/file , so my cron job should run that every hour, is it possible to do this in a cron job ?, any help would be appreciated

terdon avatar
cn flag
Why do you need `sudo`? What does this script do? You can't use `sudo` in cron, but in order to give a working solution, we need to understand if it is actually needed.
cn flag
You'll want to read [`man 5 crontab`](https://manpages.ubuntu.com/manpages/focal/en/man5/crontab.5.html) to learn about the format. And do `sudo crontab -e` to edit **root**'s crontab instead of putting sudo in your crontab.
Score:1
es flag

That is completely possible. Just add the entry on the crontab file with crontab -e using the correct user. You can also move your script at /etc/cron.hourly. Just take in count that bash files under /etc/cron.hourly will run under root. If you want to run your script under a target user, use the crontab approach and make sure to provide the absolute path of your script and your user can execute the script. e.g

@hourly /my/bash/script.sh
#or
0 * * * * /my/bash/script.sh
cn flag
thanks for answering, I have some doubts. How can I move my script to the /etc/cron.hourly folder, if I want it to run as root, or what way to do it is more efficient for this case? And another question, my command uses bash, do I have to put the absolute path to bash and also to the file that I want to execute?
Javier Galarza avatar
es flag
Can you provide the command or script that you want to run in cron?
cn flag
It is a command that executes a file to clear the cache, I execute it in the following way inside the folder of my web, where is said file "sudo bash ss-purge-opcache"
Javier Galarza avatar
es flag
Just create a file at `/etc/cron.hourly` : `touch /etc/cron.hourly/update.cache` and put that command inside that file. You do not need to use the `sudo` since that script will run as root. Also, provide the correct permissions `chmod a+x /etc/cron.hourly/update.cache`. You may need to provide absolute path, if that is the case find your absolute path of the command with `which ss-purge-opcache`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.