从$ home开始存储在PLIST中的路径不会在BASH脚本命令中扩展



我正在编写一个bash脚本来自动化我们的构建过程。我需要使用plistbuddy。

下面的键指定存储档案的路径,桌面上的文件夹:

<?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 var不会扩展到/Users/*username*/Desktop/Archives/

我通过使用相同字符串的VAR进行了测试:

ARCHIVES="$HOME/Desktop/Archives/" 
echo "$ARCHIVES" 
#expands to "/Users/*username*/Desktop/Archives/"
mkdir "$ARCHIVES/test/"
#creates the 'test' directory

由于此脚本将在未知的用户帐户下运行

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很危险!评估您无法控制的任何字符串是真的危险。

因此,您需要用实际的 value 手动替换字面的$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

最新更新