How to automate bash scripts which includes sudo commands? [duplicate]

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.


Solution 1:

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.

Solution 2:

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>