I am running Ubuntu 18.04, and do most of my code editing using VisualStudio Code. To open a file from the terminal, I run the command

code fileName.java

Once I have compiled the java code, there is also the associated .class file in the directory. This means that next time I open the file, and try to autocomplete the command using "Tab", it will autocomplete to

code fileName.

Would you please be able to show me how to change the options for the code command, so that when I type

code f

and then press Tab, it will autocomplete to

code fileName.java

rather than just

code fileName.

Add this into your .bashrc:

complete -f -X '!*.java' code

and source ~/.bashrc it once.

  • The -f will do completion on files only.
  • The -X pattern allows to define a custom pattern
  • This custom auto-completion will happen for your code command only and any completion not matching the pattern is removed from the completion list.

The best way to solve the problem is to create bash completion script.

Create new bash completion script with name java using your favorite text editor, let it be nano editor for instance:

user@pc:~$ sudo nano /etc/bash_completion.d/java

Insert the code into the script:

  local cur=${COMP_WORDS[COMP_CWORD]}

  local IFS=$'\n'
  COMPREPLY=( $( compgen -f -X '!*.java' -- $cur ) )

complete -o filenames -F _code code

Save changes and close text editor.

Finally reload bash completion rules - pay attention to 'dot' and following space before first slash:

user@pc:~$ . /etc/bash_completion

This solution has 2 advantages:

  1. The script works system wide.
  2. It supports spaces in names of files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.