1

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?

user1453345
  • 338
  • 2
  • 10

3 Answers3

3

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.
bobah
  • 18,364
  • 2
  • 37
  • 70
2

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")'
John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks, cool. By the way, how do you return an array from a function? I always get "2" "3" "3" "4", but not "2 3" "3 4". – user1453345 Jul 16 '15 at 09:38
  • @user1453345 Yes, that is what you get: _shell functions return strings_. There is no _direct_ way to return an array. The simplest _indirect_ method, if the function is running in the current shell not a subshell, is to have it create a _global_ array which you can then access. If globals are not satisfactory, some other work-arounds are discussed [here](http://stackoverflow.com/questions/10582763/how-to-return-an-array-in-bash-without-using-globals). – John1024 Jul 16 '15 at 13:09
0

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=
SMA
  • 36,381
  • 8
  • 49
  • 73