在 shell 脚本中引用路径

Quote a path in a shell script

我有一个 shell 脚本,它使用 base64 对值进行编码并将其存储在变量中。

encoded="$(cat $pathtofile|base64 -w 0)"

这一直有效,直到我得到一个 $pathtofile,其中有一个特殊字符。现在我想弄清楚如何引用 $pathtofile 以便 cat 获得正确的文件。当我这样做时

encoded="$(cat '$pathtofile'|base64 -w 0)"

我最终遇到了一个错误,因为它没有扩展 $pathtofile 而是按字面打印。我尝试了其他几种组合,但它们都会导致错误引用路径。

我怎样才能得到一个引用 $pathtofile

使用$(...).

时双引号可以嵌套
encoded="$(cat "$pathtofile" | base64 -w 0)"

就其价值而言,外引号集是可选的。变量赋值不需要它们。如果你喜欢,请删除它们。

encoded=$(cat "$pathtofile" | base64 -w 0)

此外,恭喜您赢得了 Useless Use of Cat Award

encoded=$(base64 -w 0 "$pathtofile")