bash - Go中带参数的exec命令?
问题描述
在我的 shell 中,我可以执行命令acme.sh --issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please
并获取输出。
现在我想这样做,我的代码如下:
cmd := exec.Command("bash", "-c", "acme.sh --issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please");
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("issue failed with error: %s\n", err)
}
fmt.Printf("combined out:\n%s\n", string(out))
但我得到了错误exit status 1
。
正如评论所说,我分开论点:
exec.Command("bash", "-c", "acme.sh", "--issue", "--dns", "-d exmaple.com", "--yes-I-know-dns-manual-mode-enough-go-ahead-please");
但结果是它在acme.sh
没有参数的情况下执行。
解决方案
将此脚本用作 acme.sh
#!/bin/bash
echo "$*"
使用同一目录中给出的程序,您报告的错误发生
但是,如果我将当前目录添加到 shell PATH
export PATH=.:$PATH
然后程序按预期执行,就我的版本而言
$ go run c.go
combined out:
--issue --dns -d exmaple.com --yes-I-know-dns-manual-mode-enough-go-ahead-please
好的,这就是 bash -c 将单个字符串作为命令的情况(稍后会详细介绍)
如果命令是这样发出的
cmd := exec.Command("acme.sh", "--issue", "--dns", "-d exmaple.com", "--
yes-I-know-dns-manual-mode-enough-go-ahead-please")
然后,随着稍后对您的问题状态的编辑,命令 acme.sh 将在没有参数的情况下运行。
问题在于bash -c
行为方式。
从手册页
bash 在调用时解释以下选项:
-c If the -c option is present, then commands are read from the first non-option argument command_string. If there are argu‐ ments after the command_string, they are assigned to the positional parameters, starting with $0.
在您的情况下,这意味着第一个 arg tobash -c
被接受为命令。其他 args 丢失了,因为它们是新 bash shell 的位置 args 而不是acme.sh
命令
有关更多详细信息,请参见bash -c
https://unix.stackexchange.com/questions/144514/add-arguments-to-bash-c
最后,在这种情况下我会做什么:跳过"bash" "-c"
,确保脚本有正确的 bang 行并依赖内核 binfmt 处理程序
推荐阅读
- typescript - 如何从“导出模块”块导入类型?
- java - 并行运行测试时输出一次日志文件横幅
- jsp - JSP表单如果存在,如何根据url添加参数?
- azure-devops - Azure DevOps Yaml 获取时间并增加小时数
- python - 在 Python 中初始化两个变量以指向相同的引用
- javascript - 如何在会话中仅显示一次后隐藏 div
- python - 在它们的交叉引用属性上映射两个集合
- javascript - 如何根据类型在可扩展类上重用“工厂”方法?
- python - 张量的形状与提供的形状不兼容,Keras Tuner 中的错误
- java - Java代码检测CSV文件中的特殊字符