Create Basic ZSH-Command with Auto-Completion
For this tutorial you need to have zsh and the oh-my-zsh framework installed. You can find further help in the Getting Started guide on the Github page of oh-my-zsh.
As an example we want to create a command hello that accepts multiple programming languages as a first argument and prints a hello world message. The problem is, that we are too lazy to type these programming language and want some fancy auto completion for that.
Example
Here you can see, how our command will look like, when we execute it.
> hello kotlin
Hello kotlin!> hello python
Hello python!
Our aim is to autocomplete kotlin
and python
when we press tab after the hello command.
> hello <tab>
kotlin python
Create the code
For convenience reasons we will write all of our code in the .zshrc
file in our home directory. In relation to better overview it might be better to structure the code blocks into single files. See below.
If you already have a command for which you want to create auto completion you can skip step two and three.
- Open the
.zshrc
config with your favorite text editor. In my case thats vim.
vim ~/.zshrc
2. Create a command function at the bottom of the script.
hello() {
echo "Hello $1!"
}
3. Restart your terminal to reload zshrc config. You can test your command now.
> hello kotlin
Hello kotlin!
4. Reopen .zshrc
(see step 1) and add the auto completion function for that command at the bottom of the script.
_hello() {
compadd kotlin python
}
compdef _hello hello
5. Restart your terminal again. You now can type hello and press tab for multiple times. Now you should see kotlin
and python
as autocompletable arguments.
Structure command and completion function in separate files
Especially if you have a lot of commands it might be better to put these functions in separate files and source them from the .zshrc
.
In our example:
- Create directory for all commands
> mkdir ~/.commands
2. Create and edit hello
-file in which we put our function plus completion function for the hello-command
> vim ~/.commands/hello
3. Paste content from above
hello() {
echo "Hello $1!"
}
_hello() {
compadd kotlin python
}
compdef _hello hello
4. Save file and open .zshrc
file
5. Delete hello()
, _hello()
function + compdef
line
6. Add the following line to the bottom of .zshrc
. It sources the hello file from ~/.commands
we created
source ~/.commands/hello
7. When we restart the terminal session we can use the hello command with completion the same way as it were in ~/.zshrc
directly
Thanks for reading. If you liked this article, press the clap button and checkout my YouTube Channel.