在执行由 curl 获取的脚本时将参数传递给 bash

我知道如何执行这样的远程 Bash 脚本:

curl http://example.com/script.sh | bash

或者

bash < <( curl http://example.com/script.sh )

结果是一样的。

但是如果我需要将 争论传递给 bash 脚本呢:

./script.sh argument1 argument2

我尝试了几种类似的可能性,但都没有成功:

bash < <( curl http://example.com/script.sh ) argument1 argument2
39853 次浏览

try

curl http://foo.com/script.sh | bash -s arg1 arg2

bash manual says:

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.

Other alternatives:

curl http://foo.com/script.sh | bash /dev/stdin arguments
bash <( curl http://foo.com/script.sh ) arguments

To improve on jinowolski's answer a bit, you should use:

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.

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:

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

Building on others' answers, if you want your bash script to use pipes, try:

cat myfile.txt | \
bash -c "$(curl http://example.com/script.sh )" -s arg1 arg2

Example usage:

#!/usr/bin/env bash


export MYURL="https://raw.githubusercontent.com/sohale/snippets/master/bash-magic/add-date.sh"
curl http://www.google.com | \
bash -c "$(curl -L $MYURL )" -s "       >>>>> next line 🕶👉"

If you use bit.ly to shorten the url, don't forget the -L.