有一个奇怪的问题,其中一个“全局variables”的值更新在一个函数,但更新的价值是失去了,当我检查在其他function。 任何帮助,将不胜感激。
#!/bin/bash FINAL_RESULT=""; COMMAND_RESULT=""; function init() { USERNAME="root"; DF_THRESHOLD="20"; DF_COMMAND="df -Pkh"; } function executeCommand() { local RESULT; SERVER=$(hostname); RESULT=$($1); FINAL_RESULT="$FINAL_RESULT -------------------------- Executing command : \"$1\" on \"$SERVER\" --------------------------" echo "Updating FINAL_RESULT to $FINAL_RESULT" # Updated value is present echo "$RESULT" COMMAND_RESULT="$RESULT" } function getCommandResult() { executeCommand "$1"; echo "$COMMAND_RESULT" | while read eachLine do if [ "$eachLine" != "" ]; then echo "----------- eachLine ----------- $eachLine" fi done echo "Found FINAL_RESULT as $FINAL_RESULT" # Updated values is lost } function main() { init getCommandResult "$MMGETSTATE_COMMAND" "MMGETSTATE"; } main echo "*** $FINAL_RESULT" # Even now the updated values are not found
你正在调用你的函数:
local DF_Result="$( executeCommand "$1" )"
这将在子shell中执行executeCommand
,因此任何变量所做的更改在父shell中将不可用。
while
循环在子shell中执行。 这是一个常见问题; http://mywiki.wooledge.org/BashFAQ/024