Using the following code to run the given commands or scripts:
var shell, shellArg string
if runtime.GOOS == "windows" {
shell = "powershell.exe"
shellArg = "-Command"
// Modify the command to ensure it fails on any error
command = fmt.Sprintf("try { %s } catch { exit 1 }", command)
} else {
shell = "/bin/sh"
shellArg = "-c"
// Modify the command to use 'set -e' to ensure it fails on any error
command = fmt.Sprintf("set -e; %s", command)
}
cmd := exec.Command(shell, shellArg, command)
When I execute a command or normal scripts it works like charm. But in a specific case it’s getting hung.
I have a bash script main.sh
which controls the another bash script. In the next bash script services.sh
I am using the below command to start the WebLogic services:
nohup ./startWebLogic.sh > nohup.out &
When I run main.sh script using Go, I can see it starts the services as coded in the services.sh but Go cmd.exec is coming out though main.sh
process is completed. If the main.sh
is still running then it makes sense for Go to hang and my worry is even though main.sh
is completed why Go exec.command is hung?
You didn’t provide the code for how you’re executing the command. Based on your description, I’m assuming you’re using cmd.Run()
or cmd.Output()
to execute the command, which waits until the process exits before returning.
Instead, you need to use cmd.Start()
, which starts the process in the background and returns immediately. If you need the output, you can use cmd.StdoutPipe()
and/or cmd.StderrPipe()
to get it as an io.Reader
.