user1453345
user1453345

Reputation: 338

How to drop args and pass remain down in bash?

I want to implement this function, it will drop the first elem of the shell args $@, and pass the remain args to another function. If I pass 3 elems: "1 2", "2 3", "3 4" it will drop "1 2", and pass 2 elems: "2 3" and "3 4" to another function, that function will receive two params: "2 3" and "3 4".

I don't know how to do this, it seems once I convert it to string, I can never convert it back correctly?

Any suggestions?

Upvotes: 1

Views: 328

Answers (3)

John1024
John1024

Reputation: 113914

This is an approach which doesn't use shift and therefore keeps your original $@ in tact.

First, let's create a bash array from $@:

args=("$@")

Now, let's remove the first element:

unset args[0]

We can now call another script using all but the first argument:

other_script "${args[@]}"

Specific Example

Let's create a bash array:

$ args=( "1 2" "2 3" "3 4" ) 

Let's verify that we have the array we expect:

$ declare -p args
declare -a args='([0]="1 2" [1]="2 3" [2]="3 4")'

Now, let's remove the first element:

$ unset args[0]

Let's verify that the first argument has been removed:

$ declare -p args
declare -a args='([1]="2 3" [2]="3 4")'

Upvotes: 2

SMA
SMA

Reputation: 37053

Use shift command. For e.g. if to my script (with below excerpt) i pass 1 2 3 as positional parameters:

echo “arg1= $1  arg2=$2 arg3=$3”
shift
echo “arg1= $1  arg2=$2 arg3=$3”
shift   
echo “arg1= $1  arg2=$2 arg3=$3”
Output:
arg1= 1 arg2=2  arg3=3 
arg1= 2 arg2=3  arg3= 
arg1= 3 arg2=   arg3=

Upvotes: 0

bobah
bobah

Reputation: 18864

Example

#!/bin/bash
shift
func "$@"

Documentation

$ help shift
shift: shift [n]
    The positional parameters from $N+1 ... are renamed to $1 ...  If N is
    not given, it is assumed to be 1.

Upvotes: 3

Related Questions