bash : add basic autocomplete guilde.
This commit is contained in:
parent
9155ebfa83
commit
7c460f034b
70
help/linux/bash/basic/autocomplete.md
Normal file
70
help/linux/bash/basic/autocomplete.md
Normal file
|
@ -0,0 +1,70 @@
|
|||
# Bash autocomplete basic guide.
|
||||
|
||||
Here is basic guide.
|
||||
|
||||
Lets have an example of script called admin.sh to which you would like to have autocomplete working.
|
||||
|
||||
```bash
|
||||
#!/usr/bin/bash
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
arg=$1
|
||||
|
||||
case $arg in
|
||||
option_1)
|
||||
# do_option_1
|
||||
;;
|
||||
option_2)
|
||||
# do_option_1
|
||||
;;
|
||||
shortlist)
|
||||
echo option_1 option_2 shortlist
|
||||
;;
|
||||
*)
|
||||
echo Wrong option
|
||||
;;
|
||||
esac
|
||||
|
||||
shift
|
||||
done
|
||||
```
|
||||
|
||||
Note option shortlist. Calling script with this option will print out all possible options for this script.
|
||||
|
||||
And here you have the autocomplete.sh script:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/bash
|
||||
|
||||
_script() {
|
||||
_script_commands=$(/path/to/your/admin.sh shortlist)
|
||||
|
||||
local cur prev
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
COMPREPLY=( $(compgen -W "${_script_commands}" -- ${cur}) )
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -o nospace -F _script /path/to/your/admin.sh
|
||||
```
|
||||
|
||||
Note that the last argument to complete is the name of the script you want to add autocompletion to. All you need to do is to add your autocomplete script to ~/.bashrc or /etc/bash_completion.d as:
|
||||
|
||||
```bash
|
||||
source /full-path/to/your/autocomplete.sh
|
||||
|
||||
# or
|
||||
|
||||
. /full-path/to/your/autocomplete.sh
|
||||
```
|
||||
|
||||
Finally, make them executable:
|
||||
|
||||
```bash
|
||||
chmod a+x admin.sh autocomplete.sh
|
||||
```
|
||||
|
||||
Source: https://askubuntu.com/a/483149/24155
|
||||
|
||||
[source](https://unix.stackexchange.com/a/291867)
|
Loading…
Reference in a new issue