0

This function will either use cURL or wGet to download a script and execute it with additional arguments:

wexec() {
    url=$1
    shift
    if command -v "curl" >/dev/null 2>&1; then
        curl -s $url | bash -s -- $@
    elif command -v "wget" >/dev/null 2>&1; then
        wget -qO- $url | bash -s -- $@
    else
        echo "No curl or wget found."
        return 1
    fi
}

I want to download and run the following script from a server and run it locally with passed arguments:

#!/usr/bin/env bash
hello() {
    echo Hello World!
}
echo Arguments: $@

I also want the hello function to be available in the local environment, but it's not, because I defined it in a subshell new shell, so calling wexec http://example.org/my-remote-script.sh a1 a2 a3; hello will successfully output Arguments: a1 a2 a3, but fail with hello: command not found.

Is there a way to send arguments from the local environment and still receive the functions from the remote script?

2
  • 1
    (nitpick: the bash -s you run there is not a subshell, but a completely independent shell)
    – ilkkachu
    Commented Jan 2, 2023 at 23:30
  • @ilkkachu you are right, subshell is a reserved term for commands enclosed in ( / ) which will not influence the parent scope, my bad. Commented Jan 2, 2023 at 23:34

1 Answer 1

1

It seems the current function arguments are passed to the sourced scripts automatically, so I can just do:

wexec() {
    url="$1"
    shift
    if command -v "curl" >/dev/null 2>&1; then
        \. /dev/stdin <<< "$(curl -s "$url")"
    elif command -v "wget" >/dev/null 2>&1; then
        \. /dev/stdin <<< "$(wget -qO- "$url")"
    else
        echo "No curl or wget found." >&2
        return 1
    fi
}

This was quite surprising.

I also had to source from /dev/stdin to make it work on macOS as well.

3
  • You should always double -quote your variables when you use them. For example "$url" instead of $url, and "$@" instead of $@ Commented Jan 3, 2023 at 0:14
  • @roaima even if I know those arguments will not contain spaces? Commented Jan 3, 2023 at 2:16
  • 1
    Yes. For example $@ will not work correctly unless double-quoted, and all unquoted variables are subject to parsing (in your case consider URLs containing & or ;) Commented Jan 3, 2023 at 7:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .