Running Multiple Exec Commands in the Same Shell Using Go
In the os/exec package of Go, executing multiple commands simultaneously presents a challenge. This article addresses a specific instance where executing commands sequentially and within the same shell is desired.
Problem Description
The provided code attempts to run three commands in succession:
cd path; ./configure; make
However, the second command, ./configure, fails with a "no such file or directory" error because the working directory is not set.
Solution Using a Shell
To execute commands within a single shell instance, the following approach can be used:
cmd := exec.Command("/bin/sh", "-c", "cd path; ./configure; make") err := cmd.Run()
This command invokes the shell (/bin/sh) with the option -c, which executes the provided commands sequentially in the shell. This allows cd to change the working directory for subsequent commands.
Solution Using Working Directory
Alternatively, if only a specific directory needs to be set for the commands, the working directory can be set manually:
config := exec.Command("./configure", "--disable-yasm") config.Dir = folderPath build := exec.Command("make") build.Dir = folderPath
By setting the Dir field of the command, the working directory is changed before the command is executed, ensuring that the commands run in the correct directory.
The above is the detailed content of How to Run Multiple `exec` Commands Sequentially in the Same Shell Using Go?. For more information, please follow other related articles on the PHP Chinese website!