执行 curl 获取的脚本时将参数传递给 bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4642915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing parameters to bash when executing a script fetched by curl
提问by Daniel R
I know how to execute remote Bash scripts like this:
我知道如何像这样执行远程 Bash 脚本:
curl http://example.com/script.sh | bash
or
或者
bash < <( curl http://example.com/script.sh )
which give the same result.
这给出了相同的结果。
But what if I need to pass argumentsto the bash script? It's possible when the script is saved locally:
但是如果我需要将参数传递给 bash 脚本怎么办?当脚本保存在本地时是可能的:
./script.sh argument1 argument2
I tried several possibilities like this one, without success:
我尝试了几种这样的可能性,但没有成功:
bash < <( curl http://example.com/script.sh ) argument1 argument2
回答by jinowolski
try
尝试
curl http://foo.com/script.sh | bash -s arg1 arg2
bash manual says:
bash手册说:
If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.
如果存在 -s 选项,或者在选项处理后没有剩余参数,则从标准输入读取命令。此选项允许在调用交互式 shell 时设置位置参数。
回答by Janne Enberg
To improve on jinowolski's answera bit, you should use:
要稍微改进jinowolski 的答案,您应该使用:
curl http://example.com/script.sh | bash -s -- arg1 arg2
Notice the two dashes (--) which are telling bash to not process anything following it as arguments to bash.
请注意两个破折号 (--),它们告诉 bash 不要将其后的任何内容作为 bash 的参数进行处理。
This way it will work with any kind of arguments, e.g.:
这样它就可以处理任何类型的参数,例如:
curl -L http://bootstrap.saltstack.org | bash -s -- -M -N stable
This will of course work with any kind of input via stdin, not just curl, so you can confirm that it works with simple BASH script input via echo:
这当然适用于通过 stdin 的任何类型的输入,而不仅仅是 curl,因此您可以通过 echo 确认它适用于简单的 BASH 脚本输入:
echo 'i=1; for a in $@; do echo "$i = $a"; i=$((i+1)); done' | \
bash -s -- -a1 -a2 -a3 --long some_text
Will give you the output
会给你输出
1 = -a1
2 = -a2
3 = -a3
4 = --long
5 = some_text
回答by ephemient
Other alternatives:
其他选择:
curl http://foo.com/script.sh | bash /dev/stdin arguments
bash <( curl http://foo.com/script.sh ) arguments