After doing a touch ~/foo.baz
, I want to run this simple code in my .bashrc
:
bar='~/foo.baz'
echo "$bar"; ls -l "$bar"
if [[ -f ~/foo.baz ]] # This is the old code I want to refactor
then
echo 'A: It works as expected.'
else
echo "A: The file $bar is not there."
fi
if [[ -f "$bar" ]] # This should be the 'dynamic' replacement, but doesn't work as I wish.
then
echo 'B: It works as expected.'
else
echo "B: The file $bar is not there."
fi
It gives me
~/foo.baz
ls: cannot access '~/foo.baz': No such file or directory
A: It works as expected.
B: The file ~/foo.baz is not there.
Why is this the case? How can i use the [[ -f ... ]]
syntax to check for files dynamically?
I already tried to change multiple things, such as [[ ... ]]
to [ ... ]
or "$bar"
to $($bar)
, $bar
, ``$bar`
(with one front backtick less, I don't know how to format it) and combinations of them. Non brought any different result. I also looked into this Q&A and tried -e
instead of -f
among other ideas, none of which solved my issue. bash --version
yields
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
I expect there to be an answer somewhere, but I couldn't find much that was helpful or even solve my question. If this is a duplicate, please advise on how to look for it instead of just closing or providing a link.