Search code examples
bashsudo

How to run two commands with sudo?


Is there any way how I can run two Db2 commands from a command line? They will be called from a PHP exec command.

  1. db2 connect to ttt (note that we need to have the connection live for the second command
  2. db2 UPDATE CONTACT SET EMAIL_ADDRESS = 'mytestaccount@gmail.com'

I tried this:

sudo -su db2inst1 db2 connect to ttt; db2 UPDATE CONTACT SET EMAIL_ADDRESS = 'mytestaccount@gmail.com'

The first command finishes correctly, but the second one fails with the following error message:

SQL1024N A database connection does not exist. SQLSTATE=08003

Note that I need to run this as php user. The command sudo -u db2inst1 id as php user gives me correct output.


Solution

  • sudo can run multiple commands via a shell, for example:

    $ sudo -s -- 'whoami; whoami'
    root
    root
    

    Your command would be something like:

    sudo -u db2inst1 -s -- "db2 connect to ttt; db2 UPDATE CONTACT SET EMAIL_ADDRESS = 'mytestaccount@gmail.com'"
    

    If your sudo version doesn't work with semicolons with -s (apparently, it doesn't if compiled with certain options), you can use

    sudo -- sh -c 'whoami; whoami'
    

    instead, which basically does the same thing but makes you name the shell explicitly.