Home > Mobile >  sh: how to pass a function with parameters as a parameter?
sh: how to pass a function with parameters as a parameter?

Time:03-09

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:

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

CodePudding user response:

If you want to do this right, reorder your arguments to put the function to call last.

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

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

call_function myfile.log "a function to echo something" echo_str "string to echo"
  • Related