Bash 函數為傳遞的參數賦值

Bash 函數為傳遞的參數賦值

我有以下情況:

我正在編寫一個腳本,該腳本將從配置文件(如果存在且參數存在)讀取其參數,或要求用戶輸入所述參數(如果不存在)。

由於我正在為一些參數執行此操作,因此我認為編寫函數是可行的方法。

然而,據我了解,該函數透過echoing 或將其指派給全域變數來傳回結果值。我確實想在函數中回顯螢幕,所以它必須是選項二。所以我嘗試了這個:

# parameters: $1=name of parameter, $2=user prompt, $3=value read from config.cfg
function getParameter {
    # If the value couldn't be read from the config file
    if [ -z "$3" ]; then
        # Echo the prompt
        echo "$2"
        # Read the user input
        read parameter

        # If it's empty, fail
        if [ -z "$parameter" ]; then
            echo "Parameter $1 not found"
            exit
        # Else, try to assign it to $3   <---- This is where it fails
        else
            $3="$parameter"
        fi
    fi
}

我這樣稱呼它:

getParameter "Database username" "Please enter database username" $database_username

config.cfg文件是source在調用函數之前創建的,並且$database_username是那裡的可選參數之一。

現在這顯然行不通了。我無法分配給$3並且因為我希望該方法是通用的,所以我MY_VARIABLE=$parameter也不能這樣做。

有誰對我如何實現以下所有目標有任何建議:

  1. 從其中獲取變數值config.cfg或從用戶輸入中讀取它
  2. 以通用方式執行此操作,即不要為每個參數重複上述程式碼(沒有函數)

答案1

不能 100% 確定我遵循,但假設文件config如下所示:

foo
database_user tom
bar

我們想要的明顯值是 的值database_user

在腳本中,您可以簡單地添加這樣一行:

dbUser=$(sed -nE 's/database_user (.*$)/\1/p' config)

然後變數$dbUser將包含以下資訊:

echo $dbUser 
tom

答案2

好吧,看來我解決了我自己的問題:

function getParameter {
    if [ -z "$3" ]; then
        # User read -p to show a prompt rather than using echo for this
        read -p "$2`echo $'\n> '`" parameter

        # Print to sdterr and return 1 to indicate failure
        if [ -z "$parameter" ]; then
            >&2 echo "Parameter $1 not found"
            return 1
        else
            echo $parameter
        fi
    else
        echo $3
    fi
}

透過使用,echo -p我能夠在控制台上顯示提示,並且仍然能夠使用常規echo.這樣,透過呼叫該函數,database_username=$(getParameter ...)我可以將其分配給一個變數。

相關內容