odessos
odessos

Reputation: 243

How to use regex in bash aliases

I often write ccclear instead of clear.

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

alias c\+lear='clear'

Upvotes: 8

Views: 2236

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

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

Upvotes: 8

Related Questions