2

Suppose I am in a directory like this:

:mydirectory$ ls

foo.txt

That only file. If I type a command like cat and then I tab to autocomplete (assume the ‸ character is actually the caret position and not a character for this purpose)...

:mydirectory$ cat ‸

changes to (again: the ‸ here is not a character but the caret)...

:mydirectory$ cat foo.txt ‸

But it is not the same for a command like this:

:mydirectory$ tar ‸

When tabbing I see the options to autocomplete:

A c d r t u x

And when writing something like:

:mydirectory$ tar -zxvf ‸

Then nothing is autocompleted.

My question is: how do many commands change the autocomplete rules in bash?

1 Answer 1

4

Commands don't change the autocomplete rules. The autocomplete rules are defined for the shell using scripts and functions and loaded when the shell is started. I am going to use bash as an example since I am familiar with that more than the other shells.

The rules for autocomplete in bash are defined in the script in /etc/bash_completion and supplemented by further scripts in /etc/bash_completion.d/ directory. These rules are sourced into bash when you login.

bash has a complete command that lets you easily define rules for completion. To see all the rules already defined, you can run complete -p.

Now, most distros will already define these rules for you. So, when you type tar <TAB>, there is already a rule defined by your distro to show file which match the pattern *.tar* and the options of the tar command as autocomplete suggestions. This is why when you type tar, it gives you the options A c d r t u x, but for tar -zvxf, it does not since there can be no further options after that. Now, if you out a .tar.gz file in that directory, it will suggest that as an autocomplete option since the next thing after the f option is a tar file.

The default /etc/bash_completion doesn't provide options as suggestions and doesn't filter the file types. In that case, you will also see the foo.txt file as a suggestion to tar.

You can read about creating your own rules here - https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1 and https://debian-administration.org/article/317/An_introduction_to_bash_completion_part_2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .