簡體   English   中英

Linux腳本:重新解釋環境變量

[英]Linux script: Reinterpret environment variable

我正在創建一個Bash腳本,它讀取一些其他環境變量:

echo "Exporting configuration variables..."
while IFS="=" read -r k v; do
    key=$k
    value=$v

    if [[ ${#key} > 0 && ${#value} > 0 ]]; then
        export $key=$value
    fi
done < $HOME/myfile

並有變量:

$a=$b/c/d/e

並希望撥打$a如下所示:

cp myOtherFile $a

副本的目標文件夾的結果是“$ b / c / d / e”,並顯示錯誤:

"$b/c/d/e" : No such file or directory

因為它實際上被解釋為文件夾路徑。

cp命令中使用之前,是否可以重新解釋此路徑?

聽起來你想要$HOME/myfile來支持Bash符號,比如參數擴展。 我認為最好的方法是修改$HOME/myfile ,實質上是一個Bash腳本:

export a=$b/c/d/e

並使用內置的source將其作為當前Bash腳本的一部分運行:

source $HOME/myfile
... commands ...
cp myOtherFile "$a"
... commands ...

你需要eval來做到這一點:

$ var=foo
$ x=var
$ eval $x=another_value
$ echo $var
another_value

在使用eval之前,我建議你使用這個文檔: http//mywiki.wooledge.org/BashFAQ/048

更安全的方法是使用declare而不是eval

declare "$x=another_value"

感謝最新的chepner 2。

嘗試這個

cp myOtherFile `echo $a`

暫無
暫無

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

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