Search code examples
bashzsh

Propagate all arguments following nth argument in a zsh script


If I have a script like

curl --socks5-hostname "127.0.0.1:${2-1080}" $1 

I can do:

purl bing.com 1081

Meaning:

curl --socks5-hostname "127.0.0.1:1081" bing.com

Now I want to dynamically add new arguments like:

purl bing.com 1081 --connect-timeout 1

How would I be able to do it?

If I use

curl --socks5-hostname "127.0.0.1:${2-1080}" $1 "$@"

Then it would end up as:

curl --socks5-hostname "127.0.0.1:1081" bing.com bing.com 1081 --connect-timeout 1

This is not the desirable outcome...

I would like:

curl --socks5-hostname "127.0.0.1:1081" bing.com --connect-timeout 1

Solution

  • You can use shift to "consume" the host and optional port, so that the remaining arguments can be passed on to curl.

    host=${1:-Missing host}  # Exits if *no* arguments available.
    shift
    
    if [[ $1 =~ ^[0-9]+ ]]; then
        port=$1
        shift
    else
        port=1080
    fi
    
    curl --sock5-hostname "127.0.0.1:$port" "$host" "$@"