'how to pass a function with parameters as a parameter?

There are two shell functions like belows

function call_function {
    func=$1
    desc=$2
    log_file=$3

    $func >> ${log_file} 2>&1
    ...
}

function echo_str {
   str=$1
   echo "$str"
}

How can I pass a shell function with parameters as a parameter?

I tried this:

call_function $( echo_str "test" ) "Echoing something" /var/logs/my_log.log

but only got

command not found

I googled it but nothing helps. Thanks a lot in advance!



Solution 1:[1]

If you want to do this right, reorder your arguments to put the function to call last, and use shift to pop off the other arguments -- which will leave the function to call and its arguments in the "$@" array.

call_function() {
    local log_file desc
    log_file=$1; shift || return
    desc=$1; shift || return
    "$@" >>"$log_file" 2>&1
}

echo_str() {
    local str
    str=$1
    echo "$str"
}

#             log_file   desc                           func     args
call_function myfile.log "a function to echo something" echo_str "string to echo"

Solution 2:[2]

call_function $( echo_str "test" ) "Echoing something" /var/logs/my_log.log

This $( echo_str "test" ) call will execute echo_str "test" which will result in test, so call_function will execute:

test >> /var/logs/my_log.log 2>&1

So, you either create a dedicated function to log messages easily to a log file:

log_msg() {
    current_date=$(date -u)
    echo "[$current_date] $1" >> $2
}

or change call_function as suggested by @Darkman

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2