Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Command completion

News

Bash

Recommended  Links

Advanced navigation Bash customization Command history reuse
ksh completion Bash completion modes bash programmable completion package Unix shell history Customizing Shell Dot Files cdpath
  Sysadmin Horror Stories Unix shells history Tips Humor Etc

Introduction

One of the most powerful (and typically underused) features of  many shells (ksh, bash, zsh) is filename completion facility, introduced to Unix in C shell, and originated in DEC TOPS-20 operating system.

The idea behind filename completion is that when you need to type a filename, you should not have to type more than is necessary to identify the file unambiguously. This is an excellent idea although it is limited by absence of visual feedback (compare with OFM filename completion). Still in moderate dozes it can save you some typing.

There is also a possibility to increase efficiency of programming completion by considering the type of arguments (which can be deducted from the command and its options) that particular command accepts. For example if you have type cd command  you are interesting in the list of directories not any other type of files.

Later version of bash, starting from 3.2  has quite elaborate completion system.  Now bash offers several forms of completion, including path, file, user, host and variable completion.

In default installation RHEL and Suse bash completion is pretty primitive. You can install bash-completion package from EPEL depository for RHEL and OpenSuse for SLES.

bash completion extends bash's standard completion behavior to achieve complex command lines with just a few keystrokes. This project was conceived to produce programmable completion routines for the most common Linux/UNIX commands, reducing the amount of typing sysadmins and programmers need to do on a daily basis.

It will create among other things /etc/bash_completion file that you can source.  But /etc/profile.d/bash_completion.sh module does the trick as well.  

Debian has probably the best maintained version of this package ( bash-completion ) which has tremendous number of completion modules for various commands. You can import certain modules that make value for you into RHEL or SLES installation Just download and untar Debian source package and  select those modules that are interesting to you (.xz extension, which is not popular in RHEL or Suse,  is understood by GNU tar, use -J option).

Sometimes you need to create you own particular type of completion.  This is a very interesting and productive exercise for programs that you use often. I highly recommend you doing that if you use particular program on daily basis.  Look at An introduction to bash completion part 2 and study Debian completion package.

Using completion as a way to browse directory structure

As in case of filesystem traversal with cd command completion propose the directory based of the prefix you types, using completion in this way, you can simplify traversal to the deeply nested directories that is a hall mark of many open source (for example SGE) or commercial packages such as OpenView, Tivoli, etc.

Incremental search

A very interesting example of completion is incremental searching of command history, usually bound to C-r (Ctrl-R). This is a sort of cross between the other two: press it, and start typing a word which exists somewhere in the history. By the time you've typed enough of it to uniquely identify it, it will be available for reuse. This feature is available in bash (C-r by default), tcsh (not bound by default) and zsh (C-r by default).

Command completion capabilities is different is BASH, ksh93 and zsh  

Modern implementation of completion goes beyond file names. When you can press a key (often TAB) and the shell automatically cleverly completes the rest of the word you are typing, based on the context you are typing it in. bash offers basic filename, hostname and command completion.

Only tcsh and zsh offer fully programmable context-sensitive completion of many different types with zsh functionality clearly superior.  Later versions of bash improved the completion system making it quite usable.

The most primitive completion is when instead of typing in the arguments/options following a command, the user presses TAB TAB and the shell automatically inserts (or gives you the option of inserting)  filename  based on context of command you're editing.

In more advanced implementation type of the file matters. For example, say you want to extract files from a UNIX tape archive (.tar or .tar.gz file) of the Linux kernel source tree, which you just downloaded to the /tmp directory. You type:

tar -zxvf l[pressTab TAB]
tar -zxvf linux-2.0.38.tar.gz  

If you had chosen -xvf instead, it would complete on files ending in .tar. Say there was also a file called allmail.tar in tmp:

tar -xvf [press TAB]
tar -xvf allmail.tar  

In ksh93 it means two things:

  1. The ability to complete the path or filename from the first few letters ksh supports both command and filename completion.
  2. The ability to use the arguments of previous commands (in the history)

Bash completion modes

Programmable completion indefinitely extends the type of completion you can perform.

Bash supports several completion modes (via readline). Only few first have practical importance and return on investment for other modes might in general be negative:

complete (TAB)
Attempt to perform completion on the text before point. The actual completion performed is application-specific. Bash attempts completion treating the text as a variable (if the text begins with `$'), username (if the text begins with `~'), hostname (if the text begins with `@'), or command (including aliases and functions) in turn. If none of these produces a match, filename completion is attempted.
possible-completions (M-?)
List the possible completions of the text before point.
insert-completions (M-*)
Insert all completions of the text before point that would have been generated by possible-completions.
menu-complete ()
Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default.
delete-char-or-list ()
Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default.
complete-filename (M-/)
Attempt filename completion on the text before point.
possible-filename-completions (C-x /)
List the possible completions of the text before point, treating it as a filename.
complete-username (M-~)
Attempt completion on the text before point, treating it as a username.
possible-username-completions (C-x ~)
List the possible completions of the text before point, treating it as a username.
complete-variable (M-$)
Attempt completion on the text before point, treating it as a shell variable.
possible-variable-completions (C-x $)
List the possible completions of the text before point, treating it as a shell variable.
complete-hostname (M-@)
Attempt completion on the text before point, treating it as a hostname.
possible-hostname-completions (C-x @)
List the possible completions of the text before point, treating it as a hostname.
complete-command (M-!)
Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order.
possible-command-completions (C-x !)
List the possible completions of the text before point, treating it as a command name.
dynamic-complete-history (M-TAB)
Attempt completion on the text before point, comparing the text against lines from the history list for possible completion matches.
complete-into-braces (M-{)
Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell

Korn shell command completion

Backslash (\) is the command that tells the Korn shell to do filename completion in vi-mode. If you type in a word, type ESC to enter control mode, and then type \, one of four things will happen:

  1. If there is no file whose name begins with the word, the shell will beep and nothing further will happen.

  2. If there is exactly one way to complete the filename and the file is a regular file, the shell will type the rest of the filename, followed by a space in case you want to type in more command arguments.

  3. If there is exactly one way to complete the filename and the file is a directory, the shell will complete the filename, followed by a slash.

  4. If there is more than one way to complete the filename, the shell will complete out to the longest common prefix among the available choices.

A related command is *.  It behaves similarly to ESC \, but if there is more than one completion possibility (number four in the list above), it lists all of them and allows you to type further. Thus, it resembles the * shell wildcard character.

The command = does the same kind of filename expansion as the * shell wildcard, but in a different way. Instead of expanding the filenames onto the command line, it prints them in a numbered list with one filename on each line. Then it gives you your shell prompt back and retypes whatever was on your command line before you typed =. You can select the filename you which and put it on the command line using the middle button of the mouse.

LUG@GT Using the Korn Shell

[esc] [=]

Display list of pathnames that result from expanding the word under the cursor.

[esc] [esc]

Append characters to the word under the cursor to complete the pathname of an existing file.

[esc] [*]

Replace words under the cursor with the list of pathnames that result from expanding the word.

2.7. Command completion -- vi mode

[=]

Display list of pathnames that result from expanding the word under the cursor.

[\]

Append characters to the word under the cursor to complete the pathname of an existing file.

[*]

Replace words under the cursor with the list of pathnames that result from expanding the word.

=

Pathname listing. Causes the current word on the command line to be expanded to a list of pathnames. For example,
                    $ls m<ESC>=
                    1) myfile
                    2) myhome
                    $

\

Pathname completion. Causes the current word on the command line to be expanded to a filename or directory. If it is a directory then a / is added. For example,
                    $ echo my<Esc>\
  would expand to myfile.

@letter

Searches your list of aliases for one named _letter. If an alias is defined, its value is inserted as keystrokes. For example,
                    alias _Q='LBi"^V<Esc>Ea"^V<Esc>'
  now if you are editing a command and type <Esc>@Q the current word you are on would be quoted.

#

Insert a # (comment marker) at the beginning of a command.

The zsh extended completion

the zsh extended completion includes: the ytalk, finger and ssh commands, which complete on usernames and hostnames (automatically appending an @ symbol in between); the find command, which has different completions for each option (e.g. completes file/directory names for the initial parameter(s), users for -user, groups for -group ... zsh is even able to treat the arguments to -exec as a whole new command line!). The rpm, cvs, and gcc completions are even more fiendish.

You certainly get "hardcore hacker" points for fully grokking the internals of the zsh completion system. However, you can rejoice in the knowledge that you won't ever need to in order to enjoy this sophisticated time-saver, since the latest development versions come with a complete, `out of the box' pre-configured completions system.



NEWS CONTENTS

Old News ;-)

Please visit Heiner Steven SHELLdorado: the best shell scripting site on the Internet

An introduction to bash completion part 1

Posted by Anonymous (203.206.xx.xx) on Wed 19 May 2010 at 04:51

Anyone interested, here's my clearcase completion script for bash: http://jan.tomka.name/project/clearcase-completion-bash

An introduction to bash completion part 2

A Basic Example

As a basic example we'll first look at adding some simple completions to the binary foo. This hypothetical command takes three arguments:

To handle these arguments we'll create a new file /etc/bash_completion.d/foo. This file will be automatically sourced (or loaded) when the bash completion code is loaded.

Inside that file save the following text:

_foo() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--help --verbose --version"

    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _foo foo

To test it you can now source the file:

skx@lappy:~$ . /etc/bash_completion.d/foo
skx@lappy:~$ foo --[TAB]
--help     --verbose  --version  

If you experiment you'll see that it successfully completes the arguments as expected. Type "foo --h[TAB]" and the --help argument is completed. Press [TAB] a few times and you'll see all the options. (In this case it doesn't actually matter if you don't have a binary called foo installed upon your system.)

So now that we have something working we should look at how it actually works!

How Completion Works

The previous example showed a simple bash function which was invoked to handle completion for a command.

This function starts out by defining some variables cur being the current word being typed, prev being the previous word typed, and opts which is our list of options to complete.

The option completing is then handled by use of the compgen command via this line:

COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )

What this does is set the value of $COMPREPLY to the output of running the command:

compgen -W "${opts}" -- ${cur}

If you replace these variables with their contents you'll see how that works:

compgen -W "--help --verbose --version" -- "userinput"

This command attempts to return the match of the current word "${cur}" against the list "--help --verbose --version". If you run this command in a shell you'll be able to experiment with it and see how it works:

skx@lappy:~$ compgen -W "--help --verbose --version" -- --
--help
--verbose
--version
skx@lappy:~$ compgen -W "--help --verbose --version" -- --h 
--help

Here you first see what happens if the user enters just "--" - all three options match so they are returned. In the second attempt the user enters --h and this is enough to specify --help unambiguously, so that is returned.

In our function we simply set "COMPREPLY" to this result, and return. This allows bash to replace our current word with the output. COMPREPLY is a special variable which has a particular meaning within bash. Inside completion routines it is used to denote the output of the completion attempt.

From the bash reference manual we can read the description of COMPREPLY:

COMPREPLY
An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility

We can also see how we found the current word using the array COMP_WORDS to find both the current and the previous word by looking them up:

COMP_WORDS
An array variable consisting of the individual words in the current command line. This variable is available only in shell functions invoked by the programmable completion facilities.
COMP_CWORD
An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities
A Complex Example

Many commands are more complicated to fill out, and have numerous options which depend upon their previous ones.

As a relevant example Xen ships with a command called xm this has some basic options:

In general the command is "xm operation args" where "args" varies depending upon the initial operation selected.

Setting up basic completion of inital operation can be handled in much the same way as our previous example the only difference is that the operations don't start with a "--" prefix. However completing the arguments requires special handling.

If you recall we have access to the previous token upon the command line, and using that we can take different actions for each operation.

The sample code looks like this:

_xm() 
{
    local cur prev opts base
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    #
    #  The basic options we'll complete.
    #
    opts="console create list"


    #
    #  Complete the arguments to some of the basic commands.
    #
    case "${prev}" in
	console)
	    local running=$(for x in `xm list --long | grep \(name | grep -v Domain-0 | awk '{ print $2 }' | tr -d \)`; do echo ${x} ; done )
	    COMPREPLY=( $(compgen -W "${running}" -- ${cur}) )
            return 0
            ;;
        create)
	    local names=$(for x in `ls -1 /etc/xen/*.cfg`; do echo ${x/\/etc\/xen\//} ; done )
	    COMPREPLY=( $(compgen -W "${names}" -- ${cur}) )
            return 0
            ;;
        *)
        ;;
    esac

   COMPREPLY=($(compgen -W "${opts}" -- ${cur}))  
   return 0
}
complete -F _xm xm

Here we've setup the initial completion of the operations and then added special handling for the two operations "create" and "console". In both cases we use compgen to complete the input based upon the text that is supplied by the user, compared against a dynamically created list.

For the "console" operation we complete based upon the output of this command:

xm list --long | grep \(name | grep -v Domain-0 | awk '{ print $2 }' | tr -d \)

This gives us a list of the running Xen systems.

For the creation operation we complete based upon the output of this command:

for x in `ls -1 /etc/xen/*.cfg`; do echo ${x/\/etc\/xen\//} ; done

This takes a directory listing of the /etc/xen directory and outputs the names of any files ending in .cfg. For example:

skx@lappy:~$ for x in `ls -1 /etc/xen/*.cfg`; do echo ${x/\/etc\/xen\//}; done
etch.cfg
root.cfg
sarge.cfg
steve.cfg
x.cfg
skx@lappy:~$ 
Other Completion

Using the compgen command we've shown how to match user input against particular strings, both by using a fixed set of choices and by using the output of commands.

It is also possible to match directory names, process names, and other things. See the bash manual for a full description by running "man bash".

The final example demonstrates how to complete files and hostnames in response to two initial options:

#
#  Completion for foo:
#
#  foo file [filename]
#  foo hostname [hostname]
#
_foo() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="file hostname"
 
    case "${prev}" in
	file)
	    COMPREPLY=( $(compgen -f ${cur}) )
            return 0
            ;;
        hostname)
	    COMPREPLY=( $(compgen -A hostname ${cur}) )
            return 0
            ;;
        *)
        ;;
    esac

    COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
}
complete -F _foo foo

Using these examples you should now be able to create your own custom completion functions. 95% of the time you only need to complete from a set of available options, the other times you'll need to deal with dynamic argument generation much like we did for the xm command.

Breaking the options down into a small collection of pipes and testing them outside the completion environment (just in the shell) is probably the best approach, then once you've got a working command line just paste it into your function.

For reference my xm completion code can be found online.

bash completion

The Debian bash package features support for command line completion through the file /etc/bash_completion. This page of the chicken wiki provides a file to add completion for the chicken tools in bash. Currently, only chicken-setup is supported. Hopefully csi and csc will follow.
Copy the following code in a file named chicken in /etc/bash_completion.d. Alternatively, sourc >*.egg files.
  • chicken-setup -<tab> completes for options.
  • options.
    # chicken-setup command line completion for bash.
    #
    # version 0.2 -- 2007.01.13 -- vo minh thu 
    #  - chicken-setup  completes for *.egg files.
    # version 0.1 -- 2007.01.13 -- vo minh thu
    
    _chicken_setup()
    {
        local cur prev frst opts
        COMPREPLY=()
        cur=${COMP_WORDS[COMP_CWORD]}
        prev=${COMP_WORDS[COMP_CWORD-1]}
        frst=${COMP_WORDS[1]}
    
        opts='-help -version -repository -program-path -host \
              -uninstall -list -run -script -eval -verbose \
              -keep -csc-option -dont-ask -no-install -docindex \
              -check -test -ls -fetch-tree -tree -svn -revision \
              -local -destdir'
    
        paroptions=${opts}
    
        # the following options take zero or one argument
        case "${prev}" in
        '-repository' | '-program-path' | '-local' | '-destdir' )
            COMPREPLY=( $(compgen -A directory ${cur}) )
            return 0;;
        '-host' )
            COMPREPLY=( $(compgen -A hostname ${cur}) )
            return 0;;
        '-run' | '-script' | '-tree' )
            COMPREPLY=( $(compgen -A file ${cur}) )
            return 0;;
        '-uninstall' | '-ls' )
            local exts=$( chicken-setup -list | awk '{ print $1 }' )
            COMPREPLY=( $(compgen -W "${exts}" -- ${cur}) )
            return 0;;
        esac
    
        # the following options take zero or more arguments
        case "${frst}" in
        '-list' | '-test' )
            local exts=$( chicken-setup -list | awk '{ print $1 }' )
            COMPREPLY=( $(compgen -W "${exts}" -- ${cur}) )
            return 0;;
        esac
    
        case ${cur} in
        -* )
            COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
            return 0;;
        * )
            COMPREPLY=($(compgen -f -X "egg" -- ${cur}))
        esac
    
    }
    [ "$have" ] && complete
    

    An introduction to bash completion part 1

    Sometimes this luxury drives me crazy...

    If I have a tar file not named with suffix .tar and I type "tar xvf filenamebeginning<tab>", what will happen?

    Same effect for many other extension driven suggestions or completions...

    It is very usefull to know, that if I type "\tar" instead of "tar", command completion will not happen at all. Even if "tar was aliased, "\tar" will override this IIRC...

    But now for something (not really) completely different...

    Another nice feature for small functions or big screens is the way functions are "completed". Try

    "function _mc<tab><tab>".

    You can edit the function with bash's commandline editor and even rename the function name.

    Similar for aliases. Assume having aliased "ll" to somethig obvious then "alias ll=<tab>" gives the alias definition als editable line...

    ====

    If I have a tar file not named with suffix .tar and I type "tar xvf filenamebeginning", what will happen?
    You will try Shift-TAB (or ESC-TAB or Alt-/) instead ofTab to revert to standard filename expansion.

    A Bash Completion Script for Rant

    Rant is a build tool that uses Ruby as the underlying scripting language. It is a competitor to SCons (which uses Python as the programming language) but perhaps more especially to Rake, which like Rant is build on Ruby. There has been a lot written about the relationship of Rake and Rant elsewhere and I am not yet in a position to comment on this as I am only just beginning to try Rant having done some work with SCons and Rake.

    The problem is that whilst Rake comes with a Bash completion script, Rant does not.

    The Solution

    The solution is totally clear: create a Bash completion script for Rant. Given the similarity between Rake and Rant, and having done equivalents for SCons and Gant, it is easy to take the Rake script and edit it a bit. So I came up with a script (that you can download by clicking here) that seems to do the job. It almost certainly has error and/or bugs but for the moment it ‘works for me’.

    To use this script you can do one of:

                # -*- mode:shell-script -*-
    
                for file in bash_completion.d/*
                do
                        [[ ${file##*/} != @(*~|*.bak|*.swp|\#*\#|*.dpkg*|.rpm*) ]] &&
                                    [ \( -f $file -o -h $file \) -a -r $file ] &&
                                    . $file
                done
              

    The last has the advantage of working for all users of the machine but does require super-user privileges. I use the first (obviously).

    Turn on Bash Smart Completion

    Ubuntu Blog

    The Bash shell has this sweet feature where you can use theTab key to auto-complete certain things. For example, when I am in my home directory, the following command:

    $cd Do[TAB-key]

    will automatically yield:

    $cd Documents

    If you are an absolute novice, like I was, not so long ago, discoveringTab completion in the terminal can make you go “Wow!”. Wait till you hear the rest now

    Though you can use theTab key to complete the names of files and directories, by default the completion is pretty “dumb”. If you have already typed $cd D you would expect that theTab key would cause only the directory names to be completed, but if I try it on my machine, theTab completion tool uses filenames too.

    Now, don’t despair! There is now a smart bashTab completion trick you can use. Smart completion even complete the arguments to commands!!

    To enable smart completion, edit your /etc/bash.bashrc file. Uncomment the following lines, by removing the # in the beginning of the lines:

    #if [ -f /etc/bash_completion ]; then
    # . /etc/bash_completion
    #fi

    Now you can useTab completion to power your way through commands.

    You can even extend bash smart completion to your own favourite commands by using /etc/bash_completion, the “complete” utility and /etc/bash_completion.d . Explaining the nitty-gritty is beyond me. I refer you to the Debian Administration gurus for more information regarding smarter bash completion.

    BASH Help - A Bash Tutorial

    Basic Bash Completion will work in any bash shell. It allows for completion of:

    1. File Names
    2. Directory Names
    3. Executable Names
    4. User Names (when they are prefixed with a ~)
    5. Host Names (when they are prefixed with a @)
    6. Variable Names (when they are prefixed with a $)

    This is done simply by pressing theTab key after enough of the word you are trying to complete has been typed in. If when hittingTab the word is not completed there are probably multiple possibilities for the completion. PressTab again and it will list the possibilities. Sometimes on my machine I have to hit it a third time.

    Extended Programmable Bash Completion is a program that you can install to complete much more than the names of the things listed above. With extended bash completion you can, for example, complete the name of a computer you are trying to connect to with ssh or scp. It achieves this by looking through the known_hosts file and using the hosts listed there for the completion. This is greatly customizable and the package and more information can be found here.

    Configuration of Programmable Bash Completion is done in /etc/bash_completion. Here is a list of completions that are in my bash_completion file by default.

    An introduction to bash completion part 2

    Previously we showed how to add basic completion to commands, using facilities which were already provided by the bash completion routines. In this second part we'll demonstrate how to add completely new custom completion to commands.

    In part one we looked at adding hostname completion to arbitrary commands by executing:

    complete -F _known_hosts xvncviewer

    This uses the complete command to tell bash that the function _known_hosts should be used to handle the completion of arguments to the xvncviewer.

    If we wish to add custom completion to a command we will instead write our own function, and bind that to the command.

    A Basic Example

    As a basic example we'll first look at adding some simple completions to the binary foo. This hypothetical command takes three arguments:

    To handle these arguments we'll create a new file /etc/bash_completion.d/foo. This file will be automatically sourced (or loaded) when the bash completion code is loaded.

    Inside that file save the following text:

    _foo() 
    {
        local cur prev opts
        COMPREPLY=()
        cur="${COMP_WORDS[COMP_CWORD]}"
        prev="${COMP_WORDS[COMP_CWORD-1]}"
        opts="--help --verbose --version"
    
        if [[ ${cur} == -* ]] ; then
            COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
            return 0
        fi
    }
    complete -F _foo foo
    

    To test it you can now source the file:

    skx@lappy:~$ . /etc/bash_completion.d/foo
    skx@lappy:~$ foo --[TAB]
    --help     --verbose  --version  
    

    If you experiment you'll see that it successfully completes the arguments as expected. Type "foo --h[TAB]" and the --help argument is completed. Press [TAB] a few times and you'll see all the options. (In this case it doesn't actually matter if you don't have a binary called foo installed upon your system.)

    So now that we have something working we should look at how it actually works!

    [Dec 11, 2007] CLI Magic Bash complete By Shashank Sharma

    May 08, 2006 | Linux.com

    The auto complete feature of the Bourne Again SHell makes bash one of the most loved and newbie-friendly Linux shells. Just by pressing theTab key you can complete commands and filenames. Press theTab key twice and all files in the directory get displayed. But you can do more with autocomplete -- such as associating file types with applications, and automatically designating whether you're looking for directories, text, or MP3 files. With simple commands such as complete and the use of Escape sequences, you can save time and have fun on the command line.

    You can use the dollar sign ($), tilde (~), and at (@) characters along with theTab key to get quick results in autocomplete.

    For instance, if you want to switch to the testing subdirectory of your home directory, you can either type cd /ho[Tab]/tes[Tab] to get there, or use the tilde -- cd ~tes[Tab]. If the partial text -- that is, the portion before you pressTab -- begins with a dollar sign, bash looks for a matching environment variable. The tilde tells bash to look for a matching user name, and the at-sign tells it to look for a matching hostname.

    Escaping is good

    TheTab key can complete the names of commands, files, directories, users, and hosts. Sometimes, it is overkill to use theTab key. If you know that you are looking for a file, or only user names, then use the Escape key instead for completion, as it limits bash's completion field.

    You can use several Escape key combinations to tell bash what you are looking for. Invoke Escape key combinations by pressing a key while keeping the Escape key pressed. When looking for a file, you can use the Esc-/ (press / along with Escape) key combination. This will attempt filename completion only. If you have one file and one directory beginning with the letter 'i,' you will have to press theTab key twice to see all the files:

    $ less i <tab><tab>
    ideas im articles/

    When you type less i and press '/' while keeping the Escape key pressed, bash completes the filename to 'ideas.'

    While Control key combinations work no matter how long you keep the Ctrl key pressed before pressing the second key, this is not the case with Escape key sequences. The Esc-/ sequence will print out a slash if you delay in pressing the / key after you press the Escape key.

    You can also use Escape along with the previously discussed $, ~, and @ keys. Esc-$, for example, completes only variable names. You can use Esc-! when you wish to complete command names. Of course you need to press the Shift key in order to use any of the "upper order" characters.

    Even smarter completion

    By default,Tab completion is quite dim-witted. This is because when you have already typed cd down before pressing Tab, you'd expect bash to complete only directory names. But bash goes ahead and displays all possible files and directories that begin with 'down.'

    You can, however, convert bash into a brilliant command-reading whiz. As root, edit the /etc/bash.bashrc file. Scroll down to the end of the file till you see the section:

    # enable bash completion in interactive shells
    #if [ -f /etc/bash_completion ]; then
    #    . /etc/bash_completion
    #fi
    

    Uncomment this section and voilà, you have given bash powers far beyond your imagination! Not only is bash now smart enough to know when to complete only directory names, it can also complete man pages and even some command arguments.

    Don't despair if you don't have root previleges. Just edit the last section of your ~/.bashrc file.

    Associating application with file types

    The complete command in bash lets you associate file types with certain applications. If after associating a file type to an application you were to write the name of the application and press Tab, only files with associated file types would be displayed.

    complete -G "*.txt" gedit would associate .txt files with gedit. The downfall of using complete is that it overwrites bash's regular completion. That is, if you have two files named invoice.txt and ideas.txt, gedit [Tab][Tab] displays both the files, but gedit inv[Tab], which should complete to invoice.txt, no longer works.

    complete associations last only for the current bash session. If you exit and open a console, gedit will no longer be associated with .txt files. You need to associate file types to applications each time you start a new console session.

    For permanent associations, you need to add the command to one of the bash startup scripts, such as ~/.bashrc. Then, whenever you are at the console, gedit will be associated with .txt files.

    Shashank Sharma is studying for a degree in computer science. He specializes in writing about free and open source software for new users.

    Shashank Sharma is studying for a degree in computer science. He specializes in writing about free and open source software for new users. He is the co-author of Beginning Fedora, published by Apress.

    bash Tricks From the Developers of the O'Reilly Network - O'Reilly ONLamp Blog

    No more worrying about cases

    The best bash tip I can share is very helpful when working on systems that don't allow filenames to differ only in case (like OSX and Windows):
    create a file called .inputrc in your home directory and put this line in it:

    set completion-ignore-case on

    Now bash tab-completion won't worry about case in filenames. Thus 'cd sit[tab]' would complete to 'cd Sites/'

    Re: command completion


    > I was wondering if anyone knows if there is software (or built in
    > functionality) for the korn shell in UWin which allows for the following two
    > functions available in the Unix Cshell:
    > 
    > 1.)the ability to complete the path/filename from the first few letters
    > typed
    Yes, ksh supports both command and filename completion.  In emacs
    mode use, <ESC><ESC> to complete a command or pathname up to the
    point of uniqueness.  If the complete the first word on the line,
    then this indicates command completion and it will uses functions,
    builtins, and path search to complete the argument.  You can use
    <ESC>= to get the matching list.
    In vi-mode use <ESC> to go to control mode and then \ to
    complete or = to list.
    U/WIN provides functions emacs_keybind and vi_keybind to allow
    theTab key to be used for completion, but there is a bug in
    the emacs_keybind function in which a $ is missing in front of the '\E\E".
    
    > 2.)the ability to use the arguments of previous commands (in the history)
    In vi-mode you can use _ from control mode to get the last argument
    of the previous command, or n_ to get the n-th argument of the
    pervious command.  With emacs you can use <ESC>_ or <ESC>.
    > 
    > 
    
    David Korn
    research!dgk
    [email protected]

    freshmeat.net Project details for bash programmable completion

    Please allow user to revert to standard bash completion at any time (a must-have).
    by Stéphane Gourichon - Oct 4th 2004 07:59:13

    Currently, the arguably interesting features of bash_completion actually interfere with some completion
    patterns that bash had for years, (for example completing a path stopping at cursor, when the cursor is in the middle
    of the line, but there are other cases in previous comments).

    Generally, until it can be proven that a change makes the situation better at all times without any (even minor)
    downside, the change should be reversible and never imposed.

    So, any user should be able to turn it off. The simplest idea is to unset the involved environment variables.

    But BASH_COMPLETION and BASH_COMPLETION_DIR
    are declared as read-only. Why ?
    This prevents a particular user to turn it off... :-(

    On a system with many users, there's currently no other choice than to ask the administrator to remove the
    package for all users (or make it not activated by default, which is not what we need either).

    Is it currently possible for a user to revert to standard bash completion ? If not, please consider changing
    something in the package (even something as simple as checking for some ~/.bash_completionrc for a hint should
    be fine).

    The risk is that, on any big site, new users don't even know what comes from your package or even that it
    exists, but people that used normal bash completion completion in ways *you* don't use will dislike the package
    (becauses it causes less efficient work) and have it removed for all users.

    A last suggestion : use savannah.nongnu.org or sourceforge.net to have real forums. Freshmeat comments
    aren't structured enough so that contributors can make a good job of checking if a request was already issued
    before. User feedback quality depends on this.

    Regards,

    --
    "J'y gagne, répondit le renard, à cause de la couleur du blé."

    [»] Re: Please allow user to revert to standard bash completion at any time (a must-have).
    by Ian Macdonald - Oct 8th 2004 17:20:08


    > So, any user should be able to turn it

    > off. The simplest

    > idea is to unset the involved

    > environment variables.

    >

    > But BASH_COMPLETION and

    > BASH_COMPLETION_DIR

    > are declared as read-only. Why ?

    > This prevents a particular user to turn

    > it off... :-(

    These are set read-only, because it's bad to change them once they've been set. They are used later on and it's important that the value doesn't change. They can be set before the bash_completion script is run, however, and the original value will be honoured.

    > On a system with many users, there's

    > currently no other

    > choice than to ask the administrator to

    > remove the

    > package for all users (or make it not

    > activated by default,

    > which is not what we need either).

    >

    > Is it currently possible for a user to

    > revert to standard

    > bash completion ?

    Yes, just run 'complete -r' and all completions will be removed, leaving just the default. However, I agree that this isn't the most useful way of achieving this, so I will consider the implementation of a better mechanism.


    > A last suggestion : use

    > savannah.nongnu.org or

    > sourceforge.net to have real forums.

    > Freshmeat comments

    > aren't structured enough so that

    > contributors can make a

    > good job of checking if a request was

    > already issued

    > before. User feedback quality depends on

    > this.

    Well, e-mail works well, too. I agree that this forum isn't very efficient or convenient, so just e-mail me your comments instead. It would be nice to have a real mailing list, though. I'll consider setting one up.

    [»] Wonderful... but...
    by GaelicWizard - Oct 5th 2003 02:14:11

    I LOVE bash_completion, but I think that it is growing
    just a tad too big... and a little unmanageable.
    Spesific gripes:
    1) If $UNAME isn't tested explicitly for an OS that
    doesn't return xyz then feature abc which worx, is not
    completed upon. I'm not sure how this is fixable, its just
    a comment. :-)
    2) some of the functions and completions seem to be
    slightly more complex than neccessary. What I mean is
    that I don't see the need to redefine the builtin
    completions if the builtin ones work.
    3) It seems to be very linux spesific, although almost all
    worx on freeBSD it checks vigorously for linux in
    $UNAME.

    Thanx, keep up the good work!

    [»] Re: Automatic change directory
    by Ian Macdonald - Apr 18th 2003 18:37:42


    > Would it be possible to add the
    > automatic change directory feature to
    > Bash Completion?
    >
    > If a directory called /usr/local/lib/foo
    > exists and the command line is:
    > $ /usr/local/lib/foo <return>
    >
    > Then the action is to change to that
    > directory instead of reporting that
    > "/usr/local/lib/foo" is a
    > directory.
    >
    > I've used this feature in other shells.
    > Can this be done at the command
    > completion level or does it call for a
    > more fundamental change in bash
    > itself?
    >

    bash can't really do this, since it has no pre-execution hook for you to tap into with code.
    Nevertheless, to my surprise, I managed to botch together the following hack:

    trap '{ d=$_; [ -d "$d" ] && cd $d; unset d; }' ERR

    This does what you want, but won't stop the attempt to run a directory from displaying an error before changing to the directory.

    Recommended Links

    Google matched content

    Softpanorama Recommended

    Please visit  Heiner Steven SHELLdorado  the best shell scripting site on the Internet

    Bash Reference Manual - Commands For Completion

    An introduction to bash completion part 1

    An introduction to bash completion part 2

    Working more productively with bash 2.x by Ian Macdonald . See below his bash programmable completion package

    Bash Reference Manual Command Line Editing

    BASHISH - the good stuff.

    Advanced Bash-Scripting HOWTO - A guide to shell scripting, using Bash

    Ian Macdonalds bash programmable completion package

    freshmeat.net Project details for bash programmable completion project  by Ian Macdonald

    Looks like an overkill...

    Since v2.04, bash has allowed you to intelligently program and extend its standard completion behavior to achieve complex command lines with just a few keystrokes. Imagine typing ssh [Tab] and being able to complete on hosts from your ~/.ssh/known_hosts files. Or typing man 3 str [Tab] and getting a list of all string handling functions in the UNIX manual. mount system: [Tab] would complete on all exported file-systems from the host called system, while make [Tab] would complete on all targets in Makefile. This project was conceived to produce programmable completion routines for the most common Linux/UNIX commands, reducing the amount of typing sysadmins and programmers need to do on a daily basis.



    Etc

    Society

    Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

    Quotes

    War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

    Bulletin:

    Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

    History:

    Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

    Classic books:

    The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

    Most popular humor pages:

    Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

    The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


    Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

    FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

    This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

    You can use PayPal to to buy a cup of coffee for authors of this site

    Disclaimer:

    The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

    Last modified: October 27, 2016