有兩個 shell 函式,如下所示
function call_function {
func=$1
desc=$2
log_file=$3
$func >> ${log_file} 2>&1
...
}
function echo_str {
str=$1
echo "$str"
}
如何傳遞帶有引數的shell函式作為引數?
我試過這個:
call_function $( echo_str "test" ) "Echoing something" /var/logs/my_log.log
但只得到
command not found
我用谷歌搜索但沒有任何幫助。提前非常感謝!
uj5u.com熱心網友回復:
如果您想正確執行此操作,請重新排序您的引數以將函式放入最后呼叫,并使用shift彈出其他引數 - 這將使要呼叫的函式及其引數留在"$@"陣列中。
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"
uj5u.com熱心網友回復:
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] $1" >> $2
}
或call_function按照@Darkman 的建議進行更改
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440887.html
