Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex in bash aliases

Tags:

alias

regex

bash

I often write ccclear instead of clear.

Is it possible to use regex in an alias ? Something like :

alias c\+lear='clear'
like image 720
odessos Avatar asked Sep 12 '14 14:09

odessos


People also ask

Can you use regex in bash?

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.

Can you use aliases in bash script?

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.

Can a bash alias take argument?

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.

How do aliases work bash?

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.


1 Answers

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
like image 157
Charles Duffy Avatar answered Sep 29 '22 19:09

Charles Duffy