- Auto-complete command line arguments
- 4 Answers 4
- Использование bash completion в командной строке, собственных скриптах и приложениях. Часть 1
- How to enable autocomplete in terminal
- Enable autocomplete on TTYs for all users
- Enable autocompletion in terminal emulators for all users
- Enable autocompletion in terminal emulators for one user only
- Enable autocomplete when desired
- How to make terminal autocomplete when there are several files/directory?
- 4 Answers 4
- The codez:
- Examples:
Auto-complete command line arguments
then I will see all the possible options of the convert script, which is great. My question is how to achieve a similar functionality, using bash, ruby or python scripts?
4 Answers 4
This is an example of BASH’s smart completion. A basic description is here, a guide to writing your own extensions is here and another (Debian-based) guide is here. And here’s a fuller featured introduction to the complete command (the command that facilitates this behaviour).
Bash provides you a way of specifying your keywords, and using them to auto complete command line arguments for your application. I use vim as a wiki, task managemer and contacts. The vim helptags system lets me index the content instead of searching through it, and the speed shows it. One feature I wanted to add to this was to access these tags from outside vim.
This can be done in a straight forward way:
This takes me directly to specific content marked using this tag. However, this will be more productive if I can provide auto-completion for the tags.
I first defined a Bash function for the vim commandline. I added the following code to my .bashrc file:
function get < vim -t $1 >Now I can use get tagname command to get to the content.
Bash programmable completion is done by sourcing the /etc/bash-completion script. The script lets us add our auto-completion script /etc/bash-completion.d/ directory and executes it whenever it is called. So I added a script file called get with the following code in that directory.
_get() < local cur COMPREPLY=() #Variable to hold the current word cur="$" #Build a list of our keywords for auto-completion using #the tags file local tags=$(for t in `cat /home/anadgouda/wiki/tags | \ awk ''`; do echo $; done) #Generate possible matches and store them in the #array variable COMPREPLY COMPREPLY=($(compgen -W "$" $cur)) > #Assign the auto-completion function _get for our command get. complete -F _get get Once the /etc/bash-completion is sourced, you will get auto-completion for the tags when you use the get command.
Along with my wiki I use it for all the documentation work and at times the code too. I also use the tags file created from my code. The indexing system lets me remember the context instead of the filenames and directories.
You can tweak this system for any of the tools you use. All you need to do is get a list of the keywords for your command and give it to the Bash programmable completion system.
Использование bash completion в командной строке, собственных скриптах и приложениях. Часть 1
Системный администратор — человек ленивый. Обычно он старается сделать максимум работы, приложив минимум усилий, а для этого зачастую требуется автоматизировать многие рутинные процедуры. Например — набор полных имен хостов при создании ssh-соединения, или же длинных аргументов некоторых команд 🙂
Сегодня я попробую рассказать про использование такого функционала шелла как bash completion.
Итак, почти любая оболочка по умолчанию умеет добавлять пути к файлам и директориям:
root@mould:~# mkdir very_long_dir_name
root@mould:~# cd ve[Tab]
root@mould:~# cd very_long_dir_name/
bash (в моем случае) после нажатия клавиши Tab допишет имя диркетории (если его можно определить однозначно по первым набранным символам), или покажет варианты:
root@mould:~# ls .s[Tab]
.ssh/ .subversion/
Но при этом некоторые шеллы умеют дополнять не только пути, но и аргументы для ряда команд. Например:
root@mould:~# apt-get up[Tab]
update upgrade
Или даже более сложные конструкции:
root@mould:~# apt-get install bash-[Tab]
bash-builtins bash-completion bash-doc bash-minimal bash-static
За данный функционал в debain-based дистрибутивах (не могу ничего сказать про остальные) отвечает содержимое пакета bash-completion.
Для того, чтобы активировать возможности completion достаточно сделать следующее:
Или добавить такой вызов в ваш .bashrc файл, после чего перелогиниться:
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
Скорее всего это у вас уже написано, но закомментировано.
Попробуем начать использовать одно из самых часто требующихся комплишенов — дополнение имен хостов при доступе к ним по ssh.
Для начала потребуется отключить хеширование имен хостов в ~/.ssh/known_hosts. При «коробочных» настройках строка в этом файле выглядит примерно так:
|1|yVV33HmBny6RPYWkUB5aW+TksqQ=|f11ZL/FI9/Krfw2bqN0tBJeeq4w= ssh-rsa AAAAB3Nz__много-много-символов__2bYw== ,
что нас не устроит.
После выставления значения HashKnownHosts No в конфиг-файле ssh-клиента (/etc/ssh/ssh_config или ~/.ssh/config), и очистки .ssh/known_hosts (иначе в него будут добавляться правильный строки только для новых хостов) мы получим удобочитаемый вариант записи в known_hosts после первой попытки залогинтся на хост:
mould,11.22.33.44 ssh-rsa AAAAB3NzaC1y__много-много-символов__c2EAANq6/Ww== .
А это, в свою очередь, позволит использовать комплишен имен при установке ssh-соединения:
veshij@dhcp250-203:~ $ ssh mould[Tab]
mould mould01e
Если в вашем «подчинении» более 5-10 машин это будет весьма удобно.
И, кстати, дополнение заработает не только для ssh, а еще для ряда других программ: ping, traceroute, telnet, etc. И не только по hostname, а еще и по ip-адресу.
Если эта тема окажется интересной, в следующей части могу рассказать, как настроить дополнение команд и аргументов для ваших собственных скриптов. Например, так:
root@mould:~# my_test_script —[Tab]
—help —kill-all-humans —conquer-the-world
How to enable autocomplete in terminal
In case we don’t have the bash-completion package installed, we install it:
aptitude install bash-completion
Enable autocomplete on TTYs for all users
We look in / etc / profile for the following lines .
# enable bash completion in interactive shells
#if [-f / etc / bash_completion] &&! shopt -oq posix; then
#. / etc / bash_completion
#fi
if ["$ BASH"]; then
if [-f / etc / bash_completion] &&! shopt -oq posix; then
. / etc / bash_completion
fi
fi
The latter will activate bash_completion for all users, including root. But it will only enable it on TTYs, and not on terminal emulators.
We reset the TTY and that’s it.
As you can see, we have added an if to the original file, which confirms that the bash_completion runs only when we are in Bash. Without that conditional, GDM will give us the previously mentioned error, since GDM would be calling bash_completion, and for some reason it conflicts with xsession.
Enable autocompletion in terminal emulators for all users
We look in /etc/bash.bashrc for the following lines .
# enable bash completion in interactive shells
#if [-f / etc / bash_completion] &&! shopt -oq posix; then
#. / etc / bash_completion
#fi
. And we remove the «#» (we uncomment them), looking like this:
# enable bash completion in interactive shells
if [-f / etc / bash_completion] &&! shopt -oq posix; then
. / etc / bash_completion
fi
The latter will activate bash_completion for all users, including root. But it will only enable it on terminal emulators, and not on TTYs.
We restart any terminal and the changes will take effect.
Enable autocompletion in terminal emulators for one user only
We must create (or edit, if it exists) the file ~ / .bashrc.
We add (or search if they do not exist, but commented, as is done in /etc/bash.bashrc) so that it looks like this:
# enable bash completion in interactive shells
if [-f / etc / bash_completion] &&! shopt -oq posix; then
. / etc / bash_completion
fi
— If file we create it, we simply add these lines.
— If these lines exist but are not present, we add them to the end of the file.
— If it exists and these lines are, we simply uncomment them.
We restart the console and the changes will take effect.
Enable autocomplete when desired
We simply have to run bash_completion at the moment we want to use it. It will be deactivated once we end the session in the terminal (with the exit command) or close the terminal that we are using if we are in a graphical environment. To run it whenever we want, we do:
The content of the article adheres to our principles of editorial ethics. To report an error click here.
Full path to article: From Linux » FileLet’s UseLinux » How to enable autocomplete in terminal
How to make terminal autocomplete when there are several files/directory?
sometimes my terminal will refuse autocomplete when I press tab (e.g. «cd a» then tab), and print the list of directories instead. Sometimes it even throws a noisy, annoying sound. Any idea how to make it autocomplete in cases like this? E.g it can show abar first, and then afoo if I press tab again. I saw this is the case in windows, or some applciation in Ubuntu
4 Answers 4
Something that is a life-saver for me is to have bash cycle through the possibilities instead of showing a dumb list.
As bash is using readline for its auto-completion, add the following lines to ~/.inputrc
Once you’re satisfied and have thoroughly tested below solution for a few days/weeks, cut and paste (don’t copy!) the same settings from ~/.inputrc to /etc/inputrc which contains the system-wide settings, making this available to all users on your system (including guest).
The codez:
# mappings to have up and down arrow searching through history: "\e[A": history-search-backward "\e[B": history-search-forward # mappings to have left and right arrow go left and right: "\e[C": forward-char "\e[D": backward-char # mapping to have [Tab] and [Shift]+[Tab] to cycle through all the possible completions: "\t": menu-complete "\e[Z": menu-complete-backward
then exit your terminal (or remote terminal like putty) and open it again.
Examples:
very-complicated-command with lots of command line parameters
very-complicated-command with lots of command line parameters