如何将带参数的函数作为参数传递?

how to pass a function with parameters as a parameter?

有两个shell函数如下

function call_function {
    func=
    desc=
    log_file=

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

function echo_str {
   str=
   echo "$str"
}

如何传递带有参数的shell函数作为参数?

我试过这个:

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

但只得到了

command not found

我用谷歌搜索了它,但没有任何帮助。 非常感谢!

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

$( echo_str "test" ) 调用将执行 echo_str "test",这将导致 test,因此 call_function 将执行:

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

因此,您可以创建一个专用函数来轻松地将消息记录到日志文件中:

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

或按照@Darkman

的建议更改call_function

如果您想正确执行此操作,请重新排序您的参数以将函数调用 last,并使用 shift 弹出其他参数 -将使函数调用 及其参数 "$@" 数组中。

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

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

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