如何取消引用从文件中读取的环境变量



假设我有一个文件fi.le:

$GNUPG_HOME
$XDG_CONFIG_HOME
$XDG_DATA_HOME

在我的备份脚本中,我想实际上取消引用这些变量(通过--include-from=fi.le在rsync中(

也就是说,$XDG_CONFIG_HOME应该变成/home/user/.config

我做了一个循环检查:

while read i; do ls "$i"; done < fi.le

for i in `cat fi.le`; do ls $i; done

它会返回:

ls:无法访问"$XDG_DATA_HOME":没有这样的文件或目录

我想它将'$'视为'\$'(转义(。我该如何更改?

envsubst是您的朋友:

$ cd "$(mktemp --directory)"
$ cat > vars.txt <<'EOF'
> $HOME
> $USER
> EOF
$ envsubst < vars.txt 
/home/username
username

删除开头的$,然后使用间接变量。

while read i; do
i=${i/$/} # remove $
ls "${!i}" # use `$i` as the name of a variable
done < fi.le

如果fi.le只包含环境变量,则:

while read i; do ls "$i"; done < <(envsubst < fi.le)

最新更新