Home > Blockchain >  how to pass a function with parameters as a parameter?
how to pass a function with parameters as a parameter?

Time:03-10

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!

CodePudding user response:

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"

CodePudding user response:

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

  • Related