存储在以 $HOME 开头的 plist 中的路径不会在 bash 脚本命令中展开

Path stored in plist starting with $HOME does not expand in bash script command

我正在编写一个 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 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

由于此脚本将 运行 在未知用户帐户下,我如何强制 $HOME 正确扩展。

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{}/g')
# or ... other ways...

使用

echo "$expanded_str2"

打印

/Users/jm/tmp/somefile