SimplGy
SimplGy

Reputation: 20437

Append to variable filename in Bash

Why does this work:

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

But this does not?

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

I have tried it in ${}, $(), "". Is this not an escaping issue?

Upvotes: 1

Views: 961

Answers (2)

nu11p01n73R
nu11p01n73R

Reputation: 26667

Because tilde ~ expansions are not done in double quotes "

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

This should work in turn

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

Or

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

Upvotes: 2

Mat
Mat

Reputation: 206659

~-expansion won't happen inside a quoted string. You can get away with this:

outputFile=~/"Desktop/..."

Or this:

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

See Tilde expansion or the bash manual for more details.

Upvotes: 4

Related Questions