Ask Your Question
2

How can auto-completion and command history in Bash terminal be implemented in a script?

asked 2023-06-29 13:31:35 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-29 13:52:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-29 13:31:35 +0000

Seen: 9 times

Last updated: Jun 29 '23