Ubuntu – How to run a ‘sudo’ command inside a script

rootscriptssudo

To do a patch manually I must type this command

sudo ./playback_delete_data_patch.sh 09_delete_old_data_p.sql  

There is a space just before the 09:

sudo ./playback_delete_data_patch.sh [space] 09_delete_old_data_p.sql

How can I run this inside a script?

There are also several other commands but this one is giving trouble.

Best Answer

  • It is rarely a good idea to have sudo inside scripts. Instead, remove the sudo from the script and run the script itself with sudo:

    sudo myscript.sh
    

    That way, all commands within the script will be run with root privileges and you only need to give the password once when launching the script. If you need a particular command within the script to be run without sudo privileges, you can run it as a regular user with (thanks Lie Ryan):

    sudo -u username command 
    

    The space is irrelevant, it should not affect anything, there is always a space between a command and its arguments.

  • Related Question