linuxbashzshcompletiontilde

cd ~[TAB] doesn't behave as expected


I've encountered an unexpected bebahiour with the completion in bash/zsh in conjunction with the tab key.

When I enter cd ~ and press [ENTER] on Linux (here Ubuntu 22.04 and latest Raspberry Pi OS) the directory is changed to the home folder.

This is (afaik) called tilde expansion.

When I enter cd ~ and press [TAB] I'd expect that it simply appends / or substitutes ~ with /home/<username>/.

Instead a list with suggestions is displayed but none of these suggestions can be found in my home folder.

The first suggestion is ~_apt and when I choose this, I'm told cd: no such file or directory: /nonexistent

The next suggestion is ~avahi/ and when I choose this I end up in /var/run/avahi-daemon.

There're further suggestions such as ~backup/, ~messagebus, ~news, ~sys/, ~systemd-coredump/, etc., most work, some don't.

enter image description here

So this looks like some pre-configured list of ?shortcuts?.


Solution

  • ~<TAB> completes a username. ~string navigates to user string home directory.

    So this looks like some pre-configured list of ?shortcuts?.

    It is not, these are usernames.

    Can this be configured?

    You tagged both bash and zsh, I do not know which one of them are you using. I know bash. In bash, you can modify the bash-completion functions, depending on the version they are installed. See ex. https://github.com/scop/bash-completion/blob/4f9ad009487452cb5896cd129a7c87ac4196cb21/bash_completion#L272 .

    Why are there suggestions that doesn't work (no such file or directory: /nonexistent)?

    There are users with not existent home directories, because they are system or batch users, or there are users with home directories to which your user does not have permissions to navigate to.

    cd ~[TAB] doesn't behave as expected

    That is true. In such situations, you could consider adjusting your expectation. ~string is the standard way to reference some user home directory, there are also less known ~+ ~- ~5. See https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html /