
我有一個名為 的資料夾MyProperties
,它包含多個.properties
文件,例如1.properties
、2.properties
等3.properties
。每個文件都包含類似以下內容:
keyname=value
我應該在此處寫入什麼作為屬性文件中的值,以便對其進行分配或替換?如何在 bash 腳本中迭代這些並將值分配給鍵?
虛擬程式碼:
#!/bin/bash
valuetobepassed="something"
#iterate over each file in the folder and replace/assign value corresponding to keyname
答案1
您可以使用sed
替換文件中的值:
#!/bin/bash
new_value=5
for f_name in MyProperties/*.properties; do
sed -i "s/^keyname=.*$/keyname=$new_value/" "$f_name"
done
答案2
如果你確實有多個成對的文件varName=value
,那麼你需要做的就是來源它。因此,迭代所有.properties
文件並獲取每個文件的源代碼:
for file in /path/to/MyProperties/*.properties; do
. "$file"
done
現在您已經在腳本中定義了所有變數。為了顯示:
$ cat foo.properties
foo="bar"
$ echo "$foo" ## no value
$ . ./foo.properties
$ echo "$foo"
bar
這假設您的.properties
文件有除了變數=值對之外什麼都沒有。進行採購時,檔案的每一行都會在執行進行採購的腳本的 shell 中執行。因此,文件中的任何命令.properties
也將被執行。任何有權訪問的攻擊者MyProperties
都可以在那裡添加惡意命令。因此,僅當您可以確定文件的內容時才執行此操作。
請注意,給定的內建路徑.
包含一個/
字元(因此./foo.properties
上面的內容)很重要,否則檔案將在 的目錄中查找,$PATH
而不是在當前目錄中(在 POSIX 合規模式下bash
和不處於POSIX 合規模式時,. file
查找file
如果在 ) 中未找到,則在目前工作目錄中$PATH
。