How to use regex in bash aliases

I often write ccclear instead of clear .

Can a regex be used in an alias? Sort of:

 alias c\+lear='clear' 
+5
source share
1 answer

Not.

Aliases trigger a simple prefix replacement and are not effective enough for others.

However, in Bash 4, you can use a function called command_not_found_handle to run in this case and run the logic of your choice.

 command_not_found_handle() { if [[ $1 =~ ^c+lear$ ]]; the clear else return 127 fi } 

If you want to dynamically add new mappings:

 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 
+5
source

Source: https://habr.com/ru/post/1202432/


All Articles