Can zsh buildtins be aliased?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 16:21:21

问题


Reading What's the difference between shell builtin and shell keyword? I wondered how much I could alias stuff in the shell.

So for example instead of writing

string_with_spaces='some spaces here'
if [ -n $string_with_spaces ]; then
    echo "The string is non-empty"
fi

the challenge would be to to write something like

signvico='iuj spacetoj tie ĉi'

se ja nevakua $signvico plie vera ope nu tiam
    echo "la signvico ne estas vakua!"
eme

So I tried this

alias se='if'
alias tiam='then'
alias eme='fi'
alias ja='['
alias ope=']'
alias nevakua='-n'
alias vera='true'
alias plie='-a'
alias nu=';'
alias eĥu='echo'

But that won't work. Indeed, using -a, -n, ; and ] aliases will make the script fail. Using se ja -n $signvico -a vera ] ; tiam with the rest of the above code will work however. I guess it's all due to the corresponding code being parsed/substituted at different level of the interpreter pipeline.

But is there a way to indeed make the whole code above as expected?


回答1:


The answer is yes, it's possible in zsh, simply use the -g flag. So for example:

# utilitarian commands/builtins
alias eĥu='echo'
alias surogu='sed'

# control structure
alias se='if'
alias else='fi' # overriding `else` is not a problem it seems :)
alias tiam='then'
alias ja='['
alias -g ope=']'

# `test` flags
alias -g plie='-a'
alias -g nevakua='-n'

# sed flags
alias -g ige='-e'

# statement combinators 
alias -g nu=';'
alias -g kaj='&&'
alias -g aŭ='||'
alias -g ke='|'

signvico='iuj spacetoj spaces tie ĉi'

se ja nevakua $signvico plie vera ope nu tiam
    eĥu "la signvico ne estas vakua!"
else # literally "out of if"

# echo 'word' | sed -e 's/word/vorto/'
eĥu 'word' ke surogu ige 's/word/vorto/'

Zsh also include a -m flag to match patterns. That might useful to capture both constructions like [[ in if [[ -n 'string' ]] … and flags for a specific command. The later is especially interesting as expanding this could rapidly grow to limitation of reuse of common vocabulary pertaining to misc. flags depending on the command.



来源:https://stackoverflow.com/questions/47999451/can-zsh-buildtins-be-aliased

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!