Bash Auto-Complete: Custom Script Possibilities with a Text File
In this article, we will explore how to create a custom auto-complete script for Bash using a text file containing a list of legal hostnames. The script will accept one argument, which is actually a shorthostname. The legal hostnames are stored in a plain text file, with one entry per line.
Understanding Bash Auto-Complete
Bash auto-complete is a feature that allows users to quickly complete commands, filenames, and other arguments by pressing the Tab key. This feature is especially useful when working with long commands or file paths. Bash auto-complete is implemented using shell functions and can be customized to meet specific needs.
Creating the Text File
The first step in creating a custom auto-complete script for Bash is to create a text file containing the legal hostnames. This file should be plain text, with one entry per line. For example:
example.com
google.com
github.com
This file can be named anything, but for this example, we will name it hostnames.txt.
Creating the Custom Auto-Complete Script
The next step is to create the custom auto-complete script. This script will read the hostnames.txt file and provide auto-complete suggestions for the shellscript command. Here is an example script:
_shellscript()
{
local cur
cur=$(echo $2 | sed 's/[[:space:]]*$//')
COMPREPLY=( $(compgen -W "$(cat hostnames.txt)" -- $cur) )
}
complete -F _shellscript shellscript
This script defines a shell function called _shellscript, which is called by the Bash auto-complete system. The function reads the hostnames.txt file and provides auto-complete suggestions based on the contents of the file. The last line of the script tells Bash to use this function for auto-complete suggestions when the shellscript command is used.
Using the Custom Auto-Complete Script
To use the custom auto-complete script, simply source it in your Bash profile. For example, if the script is named shellscript_autocomplete.sh, you can source it by adding the following line to your ~/.bashrc file:
source ~/path/to/shellscript_autocomplete.sh
After sourcing the script, you can use the shellscript command with auto-complete. For example, if you type shellscript e and press Tab, Bash will suggest example.com as an auto-complete option.
- Bash auto-complete is a feature that allows users to quickly complete commands, filenames, and other arguments by pressing the Tab key.
- Custom auto-complete scripts can be created for Bash using shell functions and the
compgencommand. - The
compgencommand can read the contents of a text file and provide auto-complete suggestions based on the contents of the file. - Custom auto-complete scripts can be used to provide suggestions for specific commands or arguments.