英文:
Run a bash file with parameters with Go
问题
你想要运行一个带有参数的bash脚本,像这样:
./test.sh param1 param2
bash文件:
param1=$1
param2=$2
echo $param1
echo $param2
然而,如果参数不存在,它将无法工作。
cmd, _ := exec.Command("/bin/sh", fmt.Sprintf("./test.sh %s %s","test1","test2")).Output()
但是,如果我更改bash脚本以执行其他操作而不传递任何内容,那么它就会工作。
cmd, _ := exec.Command("/bin/sh", "./test.sh").Output()
如何在Go中将参数传递给bash文件?
英文:
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
得分: 4
sh
命令期望将要运行的脚本名称作为参数。你不应该在shell中运行sh './test.sh test1 test2'
,而应该运行sh ./test.sh test1 test2
。在Go语言中的等效方式是:
// 不太好的方式:不允许脚本选择自己的解释器
cmd, err := exec.Command("/bin/sh", "./test.sh", "test1", "test2")
如果你将一个shell脚本作为参数传递,类似于shell命令sh -c './test.sh test1 test2'
,请注意-c
参数。这是非常不好的做法(会引入严重的安全漏洞),你不应该这样做,但如果你要这样做,代码如下:
// 非常不好的方式:如果参数化了,会引入严重的安全漏洞
cmd, err := exec.Command("/bin/sh", "-c", "./test.sh test1 test2")
但你不应该这样做。将你的脚本改为具有shebang(解释器指令):
#!/bin/sh
param1=$1
param2=$2
echo "$param1"
echo "$param2"
...将其保存为yourscript
(没有.sh
扩展名!),设置可执行权限(chmod +x yourscript
),然后运行:
// 好的方式:让你的脚本选择自己的解释器
cmd, err := exec.Command("./yourscript", "test1", "test2")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论