簡體   English   中英

將帶有參數的 bash 命令傳遞給 function

[英]Passing bash commands with parameters to a function

我有一個非常大的 shell 腳本,它圍繞特定應用程序的許多日常管理任務提供標准化的流程和邏輯包裝。

為了簡化調試和維護,我嘗試創建一個 RUN function ,它可以根據標志在屏幕或日志文件 output 之間切換:

##
 # Executes the command, which is passed as $1
 # If debug mode is enabled, dump full execution output to screen
 ##
function RUN()
{
  if $debug; then
    # output to screen
    $*
  else
    # Suppress screen output, but capture all output in logs
    $* &>> $logs
  fi
}

有了這樣的想法,通過使用調試標志調用我的腳本,我可以獲得完整的 output 到屏幕:

./script -d PARAMETERS

不幸的是,我在腳本中使用這個 RUN function 取得了非常不同的成功。 我的一些功能可以正常工作,而另一些則不能。 在我添加 RUN function 包裝器之前,該腳本運行良好,但我真的需要它提供的附加功能(當它工作時)。

以下是我的腳本中 RUN function 的一些用例示例:

# Example 1, set vars for a loop
local PARAM_LIST=$(RUN "BINARY PARAM1 PARAM2 -PARAM3")
for p in ${PARAM_LIST[@]}; do
  # Stuff
done

# Example 2, basic execution with pipes
$(RUN "BINARY PARAM1 PARAM2 -PARAM3 | awk {'{ print $2,$1 }'} | xargs -n1 BINARY PARAM1 PARAM4")

# Example 3, conditional execution
for i in ${!ARRAY[@]}; do
  if [[ ! $(RUN "BINARY PARAM1 PARAM2 $i") ]]; then
    # do stuff
  fi
done

我很確定 bash 語法是我出錯的地方,但在追查根本原因時遇到了麻煩。

誰能幫忙指出我做錯了什么?

It fails because your function expects multiple command arguments (like sudo , env , xargs , find , etc), but you instead pass it a single string with a shell command (as if for su , ssh , sh -c ).

你有你的 function 期望 shell 命令代替:

function RUN()
{
  if $debug; then
    echo "Executing: $1" >&2
    # output to screen
    eval "$1"
  else
    # Suppress screen output, but capture all output in logs
    eval "$1" &>> $logs
  fi
}

您必須正確轉義所有命令:

# Fails because $2 and $1 are not being escaped:
RUN "env | awk -F= '{ print $2, $1 }'"

# Succeeds because command is correctly escaped:
RUN "env | awk -F= '{ print \$2, \$1 }'"

另一個需要考慮的選項是在調試模式下編寫整個腳本,然后選擇性地壓縮 output,這樣您就不必添加任何額外的 escaping:

# Save stdout&stderr in case we need it
exec 5>&1 6>&2

# Optionally squash output
if ! "${debug:false}"
then
  exec &>> "$logs"
fi

# This only shows output if debug is on
BINARY PARAM1 PARAM2 -PARAM3 | awk '{ print $2,$1 }' | xargs -n1 BINARY PARAM1 PARAM4

# This always writes to stderr, whether debug is enabled or not
echo "Done" >&6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM