Get all but first N arguments to a bash function

  • A+
Category:Languages

I'm aware of how to get the last argument passed to a function but I'm wondering how to get all the arguments of a function after the first two:

For instance:

function custom_scp(){     PORT=$1     USER=$2     SOURCES=`ALL_OTHER_ARGS`     scp -P $PORT -r $SOURCES $USER@myserver.com:~/ } 

So sending three files to the remote home directory would look like

$ custom_scp 8001 me ./env.py ./test.py ./haha.py 

 


You can use array slice notation:

custom_scp() {     local port=$1     local user=$2     local sources=("${@:3}")      scp -P "$port" -r "${sources[@]}" "$user@myserver.com:~/" } 

Quoting from the Bash manual:

${parameter:offset}
${parameter:offset:length}

If parameter is @, the result is length positional parameters beginning at offset.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: