Which characters are allowed in a bash alias

前端 未结 4 1715
北恋
北恋 2021-02-14 00:05

I recently added

alias ..=\'cd ..\'
alias ...=\'cd ../..\'
alias ....=\'cd ../../..\'

to my bash_aliases file. Playing around with this, I not

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 00:35

    It's always been safer to use functions instead:

    function .. { cd '..'; }
    function ... { cd '../..'; }
    function .... { cd '../../..'; }
    

    Or for a conservative preference:

    ..() { cd '..'; }
    ...() { cd '../..'; }
    ....() { cd '../../..'; }
    

    What is safer about doing it this way?

    Aliases affect first-class syntax (if, case, etc.) and its commands are specified using quotes. It's like having to use eval unnecessarily. Using functions on the other is straightforward and you know exactly how the arguments are expanded. TL;DR aliases are a hack. It's like using a #define statement in C when you can simply define a function. It's something beginners would love to compose.

    If anyone would want to define default arguments to a command, you can use command to make the function call the external command to avoid recursion. That's the right way to do it. E.g. function grep { command grep --color=auto "$@"; }

提交回复
热议问题