Misha Moroshko
Misha Moroshko

Reputation: 171359

How to remove an item in Bash array?

I would like to pass all script arguments to the foo function, and if the first argument is something, pass all the rest arguments to the bar function.

I implemented this like that:

foo() {
  if [ "$1" = 'something' ]; then
    args=("$@")
    unset args[0]
    bar $args
  fi
}

foo $@

Is that possible to simplify this?

Upvotes: 1

Views: 851

Answers (2)

rob mayoff
rob mayoff

Reputation: 385690

If you don't need the args array for anything else in foo, you can avoid it entirely as in SiegeX's answer. If you need args for some other reason, what you are doing is the simplest way.

There is a bug in your code. When you call bar, you're only passing the first element of args. To pass all elements, you need to do this:

bar "${args[@]}"

Upvotes: 3

SiegeX
SiegeX

Reputation: 140377

Yes, use shift

foo(){ 
  if [[ $1 == 'something' ]]; then
    shift
    bar "$@" 
  fi
}

foo "$@"

Upvotes: 3

Related Questions