Linux

bash + 通過 bash 腳本從文件中讀取變數和值

  • March 6, 2018

我有以下文件變數和值

# more file.txt
export worker01="sdg sdh sdi sdj sdk"
export worker02="sdg sdh sdi sdj sdm"
export worker03="sdg sdh sdi sdj sdf"

我執行 source 以讀取變數

# source file.txt

例子:

echo $worker01
sdg sdh sdi sdj sdk

到現在為止,一切都是完美的

但現在我想從文件中讀取變數並通過簡單的 bash 循環列印值我將讀取第二個欄位並嘗試列印變數的值

#  for i in ` sed s'/=/ /g'  /tmp/file.txt | awk '{print $2}' `
  do  
  echo $i
  declare var="$i"
  echo $var
  done

但它只列印變數而不是值

worker01
worker01
worker02
worker02
worker03
worker03

預期輸出:

worker01
sdg sdh sdi sdj sdk
worker02
sdg sdh sdi sdj sdm
worker03
sdg sdh sdi sdj sdf

你有export worker01="sdg sdh sdi sdj sdk",然後你=用空格替換得到export worker01 "sdg sdh sdi sdj sdk"。其中的空格分隔欄位是export, worker01, "sdg,sdh等。

拆分=並刪除引號可能更好,因此僅使用外殼:

$ while IFS== read -r key val ; do
   val=${val%\"}; val=${val#\"}; key=${key#export };
   echo "$key = $val";
 done < vars
worker01 = sdg sdh sdi sdj sdk
worker02 = sdg sdh sdi sdj sdm
worker03 = sdg sdh sdi sdj sdf

key包含變數名、val值。當然,這實際上並沒有解析輸入,如果它們碰巧在那裡,它只是刪除雙引號。

引用自:https://unix.stackexchange.com/questions/412980