Adam Griffiths
Adam Griffiths

Reputation: 792

Bash pass all arguments from function to command except for the last one

myfunc ()
{
    if [${*: -1} == "some argument"]
    then
        command anotherCommand "$@"
    elif [ ... ] 
        ...
    fi
}

How can I change "$@" so it passed all arguments to anotherCommand except the last one?

Upvotes: 1

Views: 563

Answers (2)

chepner
chepner

Reputation: 531055

Change myfunc so that the key argument comes first, then you can simply write

myfunc () {
   first=$1
   shift
   if [ "$first" = "some argument" ]; then
       command anotherCommand "$@"
   elif [ ... ]; then
       ...
   fi
}

Or, if there's some reason you need all of the original arguments in $@ in later branches, you can move the shift into the if statement:

if [ "$first" == "some argument" ]; then
    shift
    command anotherCommand "$@"
elif ...

Upvotes: 1

Matias Barrios
Matias Barrios

Reputation: 5056

You can change your script to :

myfunc ()
{
    if [${*: -1} == "some argument"]
    then
        command anotherCommand "${@:1:$#-1}"
    elif [ ... ] 
        ...
    fi
}

And you effectively will pop the last parameter.

EXAMPLE :

#!/bin/bash


myfunc ()
{
    echo "${@:1:$#-1}"
}

myfunc apple orange banana watermelon

PRINTS

$ ./some.sh 
apple orange banana

Upvotes: 5

Related Questions