Ask Your Question

Revision history [back]

Auto-completion and command history are already built-in features of the Bash terminal. However, if you want to implement them in a script, you can use the following methods:

Auto-completion:

Bash provides a programmable completion feature that allows you to add custom completion for your commands. You can use the complete command to define a custom auto-completion for a command.

For example, let's say you have a script named my_script.sh that takes a file as an argument. You can define an auto-completion function for your script as follows:

_my_script_completion() {
    local cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=($(compgen -f -- $cur))
}
complete -o default -F _my_script_completion my_script.sh

This auto-completion function uses the compgen command to generate a list of file names that match the current argument.

Command history:

The Bash terminal keeps track of the commands you type in the command history. You can access the command history using the up and down arrow keys or by using the history command.

In a script, you can use the history command to get the list of previously executed commands. For example:

history | grep my_command

This command will search for all the commands that contain the string "my_command" in the command history.

Note that the history command is a shell built-in command and is not available in other shells like sh and ksh. Also, the history is only available for the current session and is not saved between sessions, unless you enable it by setting the HISTFILE environment variable.