我经常写ccclear
而不是clear
.
是否可以在别名中使用正则表达式?就像是 :
alias c\+lear='clear'
Run Code Online (Sandbox Code Playgroud)
没有.
别名运行简单的前缀替换,并且对于其他很多东西都不够强大.
但是,在Bash 4中,您可以使用一个被调用的函数command_not_found_handle
来触发此案例并运行您选择的逻辑.
command_not_found_handle() {
if [[ $1 =~ ^c+lear$ ]]; then
clear
else
return 127
fi
}
Run Code Online (Sandbox Code Playgroud)
如果您碰巧使用zsh,则必须调用该函数command_not_found_handler
.
如果您希望能够动态添加新映射:
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
}
Run Code Online (Sandbox Code Playgroud)
通过上面的内容,您可以轻松添加新的映射:
common_typos['^ls+$']=ls
Run Code Online (Sandbox Code Playgroud)