Executing Multiple Commands within a Single Shell in Go
Running multiple commands consecutively is a common task in shell scripting. While the os/exec package in Go provides functionality for executing commands, it may not be immediately apparent how to run multiple commands within the same shell. This article provides solutions to this problem.
In the example code provided, the goal is to run cd, ./configure, and make commands in sequence. Initially, the code attempts to accomplish this by starting each command separately, but this approach fails because each command is executed in a new shell, leading to the 'no such file or directory' error for ./configure.
To execute commands within the same shell, one can use the following syntax:
cmd := exec.Command("/bin/sh", "-c", "command1; command2; command3; ...") err := cmd.Run()
Here, the shell, /bin/sh, is invoked with the -c option that allows it to interpret the provided commands. However, this method requires careful handling of user input to prevent shell injection vulnerabilities.
An alternative approach is to set the current working directory before executing the commands:
config := exec.Command("./configure", "--disable-yasm") config.Dir = folderPath build := exec.Command("make") build.Dir = folderPath
This approach ensures that the commands are executed in the specified directory without relying on the shell. It mimics the behavior of running cd path and then executing ./configure and make within the same terminal session.
The above is the detailed content of How to Execute Multiple Shell Commands Sequentially in Go?. For more information, please follow other related articles on the PHP Chinese website!