我经常写ccclear
而不是clear
。
是否可以在别名中使用正则表达式?像这样的东西:
alias c\+lear='clear'
最佳答案
没有。
别名运行简单的前缀替换,并且功能不够强大。
但是,在 Bash 4 中,您可以使用名为 command_not_found_handle
的函数来触发这种情况并运行您选择的逻辑。
command_not_found_handle() {
if [[ $1 =~ ^c+lear$ ]]; then
clear
else
return 127
fi
}
如果你恰好在使用 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
}
通过上面的内容,您可以轻松添加新的映射:
common_typos['^ls+$']=ls
关于regex - 如何在 bash 别名中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810741/