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.
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
Asked: 2023-06-29 13:31:35 +0000
Seen: 9 times
Last updated: Jun 29 '23
What is the process for installing SASS/Compass in the DDEV web container?
Is it possible to create and execute a file without having to type the file name twice?
How can you obtain the sha1 of the most recent commit in a git repository using C#?
What is the process for initializing Java UDFs in Spark?
How can I use crontab to initiate and modify the libcamera-vid RTSP stream on my Raspberry Pi?
Is it possible to repair a file within a docker container that has failed to start?
What is an effective way to edit HTML strings using PowerShell?