I often write ccclear
instead of clear
.
Is it possible to use regex in an alias ? Something like :
alias c\+lear='clear'
Regex is a very powerful tool that is available at our disposal & the best thing about using regex is that they can be used in almost every computer language. So if you are Bash Scripting or creating a Python program, we can use regex or we can also write a single line search query.
A BASH Alias is a map of commands with the sets of commands or functions that can be used as a shortcut in the command line for a BASH environment. Bash Alias allows to aggregate multiple functions into a single command and also it avoids repetitive or large commands into a simple shortcut command.
Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.
A Bash alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding typing a long command sequence. If, for example, we include alias lm="ls -l | more" in the ~/. bashrc file, then each lm [1] typed at the command-line will automatically be replaced by a ls -l | more.
No.
Aliases run simple prefix substitution, and aren't powerful enough for much else.
However, in Bash 4, you can use a function called command_not_found_handle
to trigger on this case and run logic of your choice.
command_not_found_handle() {
if [[ $1 =~ ^c+lear$ ]]; then
clear
else
return 127
fi
}
If you happen to be using zsh, the function must be called command_not_found_handler
.
If you wanted to be able to add new mappings dynamically:
declare -A common_typos=()
common_typos['^c+lear$']=clear
command_not_found_handle() {
local cmd=$1; shift
for regex in "${!common_typos[@]}"; do
if [[ $cmd =~ $regex ]]; then
"${common_typos[$regex]}" "$@"
return
fi
done
return 127
}
With the above, you can add new mappings trivially:
common_typos['^ls+$']=ls
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With