附加到 Bash 中的变量文件名

Append to variable filename in Bash

为什么这样做:

echo "foo" >> ~/Desktop/sf-speedtest-output.csv

但这不是吗?

outputFile="~/Desktop/sf-speedtest-output.csv"
echo "foo" >> $outputFile # Error: No Such file or directory

我在${}$()""都试过了。这不是转义问题吗?

因为波浪号 ~ 扩展不是用双引号引起来的 "

If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix

这应该反过来

outputFile="/home/user/Desktop/sf-speedtest-output.csv"
echo "foo" >> $outputFile

outputFile=~/"Desktop/sf-speedtest-output.csv"
echo "foo" >> $outputFile

~-引号内不会发生扩展。你可以摆脱这个:

outputFile=~/"Desktop/..."

或者这样:

outputFile="$HOME/Desktop/..."

有关详细信息,请参阅 Tilde expansion or the bash manual