How to run two commands with sudo?
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.
How to run multiple commands while using sudo as another user
Bash supports a -c
flag that lets you specify the command to run as a command-line argument — basically an inline Bash script. That means you can easily combine multiple commands into a single call to bash
, which is then easily sudo
-ed:
sudo -i -u john.smith bash -c 'whoami ; cd /tmp/ ; ls -ltr'
or
sudo -i -u john.smith \
bash -c ' whoami
cd /tmp/
ls -ltr
'
(Other shell languages have the same feature.)
How to sudo su; then run command
Unless you have an unusual setup, you can't normally string su
with other preceding commands like that. I would imagine it is running sudo su
, then hanging in the root environment/session, because it's waiting for you to exit before preceding to the pm2
commands. Instead, I would consider something along the lines of this using the -c
option:
CMD="sudo su -c 'pm2 restart 0; pm2 restart 1'"
ssh -i somepemfile.pem ubuntu@1.1.1.1 "$CMD"
As suggested in another answer, it would also probably be useful to encapsulate the $CMD
variable in quotes in the ssh
call.
Whats the best way to switch user and run multiple commands?
Running multiple commands separated by semicolons requires a shell. To get such shell features, you must invoke a shell like, in this case, bash:
sudo -u user bash -c 'command1; command2; command3; command4; command5' > out.log 2&1
Here, sudo -u user bash
runs bash
under user
. The -c
option tells bash
which commands to run.
Related Topics
How Can a Process Try to Access Other Process's Memory in Linux Virtual Memory System
Looping Through Lines in a File in Bash, Without Using Stdin
How to Prevent Tar from Overwriting an Existing Archive
Difference Between --Cap-Add=Net_Admin and Add Capabilities in .Yml
Light-Weight SQL Server for Linux/Windows
Dynamic Loading of Shared Objects Using Dlopen()
How to Redirect Output of Echo Over Ssh to a File
Assembly Linux System Calls VS Assembly Os X System Calls
How to Install Valgrind Properly
Docker: Ssh Access Directly into Container
How to Convert a Linux Executable File (Binary) to Windows Exe File
Why Non-Pic Code Can't Be Totally Aslr Using Run-Time Fixups