There are a couple of issues with your code:
Quotes don't nest. "a"b"c"
is not a string containing a"b"c
, it is a quoted a
followed by an unquoted b
followed by a quoted c
.
Even if you fixed (1), you try to parse the "command" (arg 2) multiple times.
- First the code is obtained from
curl
and is (intended to be) stored in a string as an argument to a bash call.
- Second, the function runs
$2
which performs word-splitting. However, it will not do things like redirection, parameter expansion, variable assignments, and so on. c1 a; c2
when passed in becomes command c1
with two arguments, not c1
with one argument followed by another command c2
.
For example:
$ v="a"b"c"
$ echo "$v"
abc
$ p()($1)
$ p "echo hello && echo world >/dev/null &"
hello && echo world >/dev/null &
$ v='echo hello; n=10; echo $n'
$ p "$v"
hello; n=10; echo $n
$
The data returned by curl
is a program, so it is appropriate to pass it to bash -c
(assuming you trust it not to be malicious). However, to avoid multiple parses, it makes more sense to call bash only when you actually want to execute the code.
For example:
install_package(){
bash -c "$2" || exit $?
}
Invoke as:
if code=$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh); then
install_package "brew" "$code"
fi