取得傳遞給腳本的參數值,從另一個腳本匯入變數

取得傳遞給腳本的參數值,從另一個腳本匯入變數

我正在嘗試將變數從腳本匯出到主腳本,並將導入的變數之一作為參數傳遞給主腳本。

這是僅包含變數的腳本fruitcolour.sh

apple="Red"
mango="Yellow"
orange="Orange"
pear="Green"

這是主要腳本GetFruitColour.sh

#!/bin/bash

source fruitcolour.sh

echo "The colour of " $@ " is " $@ "."

為了作為參數傳遞,我想取得變數ieapple的值。appleRed

所以,當我跑步時./GetFruitColour.sh apple

它必須給出輸出::The colour of apple is Red.

答案1

實現此目的的一種方法是透過間接—從第一個變數的值引用另一個變數。

展示:

apple="Red"
var="apple"
echo "${!var}"

結果是:

Red

因為 bash 首先!var表示變數的值var,然後透過 解釋該值${apple}並將其轉換為Red.

因此,您的 GetFruitColour.sh 腳本可能如下所示:

#!/bin/bash

source ./fruitcolour.sh

for arg in "$@"
do
  printf 'The colour of %s is %s.\n' "$arg" "${!arg}"
done

我已經將來源腳本的路徑設置為相對路徑而不是裸路徑,以便更清楚地顯示文件的位置(如果給定的文件名不包含斜杠,shell 將搜索該$PATH變量,這可能會讓您感到驚訝) 。

我也曾echo變成printf

功能上的改變是使用循環變數$arg及其間接擴展來產生所需的值:

$ ./GetFruitColour.sh apple mango
The colour of apple is Red.
The colour of mango is Yellow.

請注意,這裡沒有錯誤檢查:

$ ./GetFruitColour.sh foo
The colour of foo is .

您可能會發現使用關聯數組更容易:

declare -A fruits='([orange]="Orange" [apple]="Red" [mango]="Yellow" [pear]="Green" )'

for arg in "$@"
do
  if [ "${fruits["$arg"]-unset}" = "unset" ]
  then
    echo "I do not know the color of $arg"
  else
    printf 'The colour of %s is %s.\n' "$arg" "${fruits["$arg"]}"
  fi
done

答案2

您需要使用間接變數引用:

如果parameter的第一個字元是感嘆號(!),且parameter不是nameref,則它引入了間接層級。 Bash 將剩餘的參數展開後所形成的值作為新參數;然後將其擴展,並且該值將用於擴展的其餘部分,而不是原始參數的擴展。這稱為間接擴展。

水果顏色.sh:

#!/bin/bash

source fruitcolor.sh

echo "The color of $1 is ${!1}"

$ ./getfruitcolor.sh apple
The color of apple is Red

相關內容