I want to write some text to a file in my home area, which doesn't yet exist. I've stored the name of the file I want to create in a variable. I want to use this variable to echo
some text and redirect it to the file, creating the file in the first place. But it doesn't work:
$ foo="~/bar"
$ echo "nonsense" > "$foo"
$ bash: ~/bar: No such file or directory
Yet it works fine if I use any other directory (provided the directory exists)
$ foo="moo/bar"
$ echo "nonsense" > "$foo"
I thought I could at least use touch
, but that also doesn't work:
$ foo="~/bar"
$ touch "$foo"
What's the necessary secret to creating a file in your home area using a file name stored in a variable?