2

I want to create a bash function bar that takes a function foo as an argument but have foo also take parameters.

function foo() {
    foo_args=("$@")
    for i in "${foo_args[@]}";
        do
            echo "$i"
        done
}

function bar() {
        ($1) 
}

foo_args=(
        "one" "two" "three"
)

bar foo foo_args

How do I pass foo_args to bar?

EDIT:

I tried:

bar foo "${foo_args[@]}"

With:

function bar() {
        params="${3}"
        ($1 ${params[@]}) 
}

But foo only looks at the first element.

2
  • What is your purpose of this code? Your bar() function has no meaning at all. Also your foo() function never gets invoked Commented Mar 14, 2019 at 5:09
  • My bar function is a function called action_needed, and foo is any action that actually performs something. foo's arguments are what foo acts on. There might be many actions needed, but they all have the same warning message. Commented Mar 14, 2019 at 5:11

1 Answer 1

1

It is not quite sure what you are intending to do with your foo() and bar() functions, but in the function bar you are not receiving the entire positional arguments, but just $1, use $@ instead. I've modified the code to suit your requirements assuming you need to pass the arguments from bar() to foo(). Since your first argument contains the function name get it in $1 and use shift to drop $1 and have rest of the arguments under $@

Also drop the non-standard function keyword from the function definition. It is perfectly OK to not mention it

#!/usr/bin/env bash

foo() {
    foo_args=("$@")
    for arg in "${foo_args[@]}"; do
        echo "$arg"
    done
}

bar() {
    function=$1; shift

    [ "$(type -t "$function")" = function ] || 
        { echo "$function prototype is not available" >&2; return 1 ; }

    "$function" "$@"
}

foo_args=(
    "one" "two" "three"
)

bar foo "${foo_args[@]}"

Also it is safe to check using type -t to ensure the prototype for the function invoked exists and throw an error message if not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.