Run a bash file with parameters with Go

Viewed 191

I am trying to run a bash script that has parameters like so:

./test.sh param1 param2

bash file

param1=$1
param2=$2

echo $param1
echo $param2

However it does not work but it will work if the params are not there.

cmd, _ := exec.Command("/bin/sh", fmt.Sprintf("./test.sh %s %s","test1","test2")).Output()

But if I change the bash script to do something else without passing anything into it, then it works.

cmd, _ := exec.Command("/bin/sh", "./test.sh").Output()

How can I pass parameters into a bash file with Go?

1 Answers

sh expects the name of a script to run as its argument. You don't run sh './test.sh test1 test2' at a shell, you run sh ./test.sh test1 test2. The equivalent to that in Go is:

// KINDA BAD: Doesn't let the script choose its own interpreter
cmd, err := exec.Command("/bin/sh", "./test.sh", "test1", "test2")

If you were passing a shell script as an argument, that would be akin to the shell command sh -c './test.sh test1 test2' -- notice the -c argument. It's very bad practice (introduces serious security bugs), and you shouldn't ever do this, but if you were going to, it would look like:

// VERY BAD: Introduces serious security bugs if arguments are parameterized
cmd, err := exec.Command("/bin/sh", "-c", "./test.sh test1 test2")

But you shouldn't do any of that. Change your script to have a shebang:

#!/bin/sh
param1=$1
param2=$2

echo "$param1"
echo "$param2"

...save it as yourscript (no .sh!), set it to have executable permissions (chmod +x yourscript), and then run:

// GOOD: Lets your script choose its own interpreter
cmd, err := exec.Command("./yourscript", "test1", "test2")
Related