0

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?

psychoslave
  • 2,783
  • 3
  • 27
  • 44

1 Answers1

0

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.

psychoslave
  • 2,783
  • 3
  • 27
  • 44