#StackBounty: #bash #shell #zsh #autocomplete How does Bash/Zsh identify the relevant command during completion?

Bounty: 50

When I start typing something into an interactive login shell (zsh or bash) and click tab, the shell offers me autocomplete suggestions.

I broadly understand how completion specs are defined. For reference it’s outlined here:

What I don’t understand is how bash/zsh identify which command to complete on when a user presses tab i.e. if I do ls [tab], how does bash/zsh identify ls. Put differently, how do bash/zsh know to generate completions using the ls completion spec.

Some more examples with more complicated parsing which Bash/Zsh still get right:

  • ls [tab] -> completes on ls
  • echo $( echo $(ls [tab] -> completes on ls
  • echo hi; git a[tab] -> completes on git
  • echo 'cd [tab] -> does NOT complete on cd
  • echo "$(ls [tab] -> completes on ls
  • echo $( echo hi | ls [tab] -> completes on ls
    (I know ls doesn’t take stdin but this example still illustrates bash/zsh’s parsing abilities)

I am presuming bash/zsh are using some sort of parser. However, it’s not a normal parser. It completes without a properly structured command. It is aware that something is in quotes or a shell expansion, even if they are not closed.

What function is bash/zsh running to "identify" the relevant command or determine whether or not there is a command to complete on at all?

Get this bounty!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.