2017-02-22 22 views
1

我正在編寫一個bash腳本來自動執行構建過程。我需要在設置plist文件中存儲路徑,並使用plistbuddy在shell腳本中檢索它。

下鍵指定了檔案將被存放的路徑,在桌面上的文件夾:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
    <key>archives_path</key> 
    <string>$HOME/Desktop/Archives/</string> 
</dict> 
</plist> 

在我的shell腳本我訪問密鑰:

SETTINGS_PATH="path/to/plist/file" 

ARCHIVES=$(/usr/libexec/PlistBuddy -c "Print archives_path" "$SETTINGS_PATH") 
#outputs "$HOME/Desktop/Archives/" 

mkdir "$ARCHIVES/test/" 
#outputs "mkdir: $HOME/Desktop/Archives: No such file or directory" 

ARCHIVES變種是不是正如我所料,擴大到/Users/*username*/Desktop/Archives/

我做了一個測試用相同的字符串創建一個變種:

ARCHIVES="$HOME/Desktop/Archives/" 

echo "$ARCHIVES" 
#expands to "/Users/*username*/Desktop/Archives/" 

mkdir "$ARCHIVES/test/" 
#creates the 'test' directory 

由於該腳本將未知的用戶帳戶,我怎麼能強迫$ HOME適當擴大下運行。

+0

試着用''選項-p' mkdir'。 – Cyrus

+0

@Cyrus'mkdir -p $ ARCHIVES'在桌面上創建一個名爲'$ HOME'的文件夾,其中包含文件夾'Desktop/Archives/test /'。 – demosp

回答

1

PlistBuddy返回的$ARCHIVE包含文字$HOME

簡單的演示:

str='$HOME/tmp/somefile' 
echo "The HOME isn't expanded: [[$str]]" 

它打印:

The HOME isn't expanded: [[$HOME/tmp/somefile]] 

您可以使用eval對於像擴展:

expanded_str1=$(eval "echo $str") 
echo "The HOME is DANGEROUSLY expanded using eval: [[$expanded_str1]]" 

它打印

The HOME is DANGEROUSLY expanded using eval: [[/Users/jm/tmp/somefile]] 

但是使用eval是危險的!評估任何並非完全在你控制之下的字符串是確實是危險。

因此,您需要手動將文字$HOME替換爲其實際的。它可以用許多方法來完成,例如:

expanded_str2="${str/\$HOME/$HOME}" 
# or 
expanded_str2=$(echo "$str" | sed "s!\$HOME!$HOME!") 
# or 
expanded_str2=$(echo "$str" | perl -plE 's/\$(\w+)/$ENV{$1}/g') 
# or ... other ways... 

使用

echo "$expanded_str2" 

打印

/Users/jm/tmp/somefile