Home > Backend Development > Golang > How to Run Multiple `exec` Commands Sequentially in the Same Shell Using Go?

How to Run Multiple `exec` Commands Sequentially in the Same Shell Using Go?

Susan Sarandon
Release: 2024-11-26 17:43:11
Original
952 people have browsed it

How to Run Multiple `exec` Commands Sequentially in the Same Shell Using Go?

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
Copy after login

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()
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template