Score:6

How to automate bash scripts which includes sudo commands?

tm flag

I added some commands to the bash script and those commands need root permission. So then I added sudo keyword to those commands. As the normal way, I added this script to the crontab file to automate my task.

Is there any way to give root access when it tries to run automatically?

Note: I'm using crontab to automate my script.

ar flag
Welcome to Ask Ubuntu. If one of the answers below solves your problem please mark that answer as correct by clicking on the gray check mark ✓ and turn it green ✅. This will help others.
Score:11
it flag

Yes. Read man sudoers sudoedit. You can give a single user passwordless access to a set of commands. You can specify a date range for the access, so if your script is only run between 03:00 and 03:15, you can allow access only then.

Score:9
hr flag

Unless you need other commands in the script to run as a non-root user, the simplest option is to remove the sudo commands from inside the script, and run the whole thing as root either by adding it to root's crontab file (sudo crontab -e) or via the system-wide /etc/crontab file specifying root in the user field.

If you do need to run some commands as a non-root user, then you can do the same but drop privileges for those specific commands using sudo -u <otheruser>

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.