DEV Community

Michael
Michael

Posted on • Originally published at gbase8.cn

Running Multiple Commands with sudo (Including source) in Linux

When managing a gbase database cluster, you often need to execute commands as the gbase user or with root privileges. Using sudo to run source directly fails because source is a shell built-in, not an external command. This article shows how to use sudo sh -c to chain multiple commands, correctly load environment variables, and handle special characters in Python scripts.

Direct sudo source Fails

Attempting to run source directly with sudo produces a “command not found” error:

[zxt2000@anolios86-1 ~]$ sudo source /home/gbase/.gbase_profile
sudo: source: command not found
Enter fullscreen mode Exit fullscreen mode

Putting multiple commands in a string also fails:

[zxt2000@anolios86-1 ~]$ sudo "source /home/gbase/.gbase_profile;gccli"
sudo: source /home/gbase/.gbase_profile;gccli: command not found
Enter fullscreen mode Exit fullscreen mode

Using sudo sh -c to Execute Multiple Commands

The solution is to spawn a child shell with sudo sh -c and pass the full command sequence as a string. If your commands contain double quotes or $ signs, escape them with a backslash.

[zxt2000@anolios86-1 ~]$ sudo sh -c "source /home/gbase/.gbase_profile;gccli -e\"show processlist\""
+----+-----------------+-----------+------+---------+-------+-----------------------------+------------------+
| Id | User            | Host      | db   | Command | Time  | State                       | Info             |
+----+-----------------+-----------+------+---------+-------+-----------------------------+------------------+
|  1 | event_scheduler | localhost | NULL | Daemon  | 12775 | Waiting for next activation | NULL             |
| 41 | root            | localhost | NULL | Query   |     0 | NULL                        | show processlist |
+----+-----------------+-----------+------+---------+-------+-----------------------------+------------------+
Enter fullscreen mode Exit fullscreen mode

Handling Special Characters in Python

When building a sudo command in Python, escape double quotes and dollar signs before wrapping the entire command inside sudo sh -c.

cmd = "sudo sh -c \"" + cmd.replace('"', '\\"').replace('$', '\\$') + "\""
Enter fullscreen mode Exit fullscreen mode

Summary

Using sudo sh -c is the cleanest way to run multiple commands that include shell built-ins like source. This technique is particularly useful in gbase database operations, where you frequently need to switch to the gbase user and load its environment before executing database commands.

Top comments (0)