Tilde expansion

(Using Bash 4.4)
When I write something like

dir="~/dox"
ls $dir

then I get the message that the directory '~/docs' does not exist. I understand that the tilde is not expanded at the time of the above assignment because of the quotes. But why is it not expanded at the time when the ls command is executed?

I also understand that at that time tilde expansion occurs before parameter expansion. But isn't the tilde available for extension at that time? After the initial assignment dir has the value ~docs.

$ echo $dir
~docs

Then at the time of executing

ls $dir

that should be the same as writing

ls ~docs

.What am I missing?

Please carefully proofread your posts before you hit the submit button. Like the shells you will be using, the people who read this forum and try to help you with problems you're having tend to read code VERY literally. So, if you start out with:

dir="~/dox"

there is absolutely no way that the command:

echo $dir

is going to produce the output:

~docs

Instead of that output, it is going to produce the output:

If we can't run the code you show us and get the same output you say you're getting, it raises all sorts of questions that can waste a lot of time for everyone involved.

Moving on to your other questions...
As you said tilde expansion is performed before parameter expansion (and it is performed by the shell, not by the kernel and not by all of the utilities {such as ls } that you ask the shell to invoke for you). So, if parameter expansion produces output containing a tilde, that tilde won't be expanded.

Note that although ls doesn't perform tilde expansion, there are some commands that you can invoke in the shell that will perform tilde and other expansions. These include, but are not limited to, invoking another shell or invoking eval .

So, to get what you seem to want to do you can use any of the following (and hundreds of other possibilities):

dir=~/docs
ls "$dir"
dir=/docs
ls ~"$dir"
dir=docs
cd
ls "$dir"
dir=docs
ls "$HOME/$dir"
1 Like

I'm sorry for the typo. You're right, the output of the command is ~/docs. I probably should have copy/pasted from the terminal but I extracted the problem from a more complex piece of code and the error occurred during that transcription.

.