Make a Bash alias that takes a parameter?

后端 未结 20 2008
长发绾君心
长发绾君心 2020-11-21 06:53

I used to use CShell (csh), which lets you make an alias that takes a parameter. The notation was something like

alias junk=\"mv \\\\!* ~/.Trash\"

20条回答
  •  时光取名叫无心
    2020-11-21 07:18

    NB: In case the idea isn't obvious, it is a bad idea to use aliases for anything but aliases, the first one being the 'function in an alias' and the second one being the 'hard to read redirect/source'. Also, there are flaws (which i thought would be obvious, but just in case you are confused: I do not mean them to actually be used... anywhere!)

    ................................................................................................................................................

    I've answered this before, and it has always been like this in the past:

    alias foo='__foo() { unset -f $0; echo "arg1 for foo=$1"; }; __foo()'
    

    which is fine and good, unless you are avoiding the use of functions all together. in which case you can take advantage of bash's vast ability to redirect text:

    alias bar='cat <<< '\''echo arg1 for bar=$1'\'' | source /dev/stdin'
    

    They are both about the same length give or take a few characters.

    The real kicker is the time difference, the top being the 'function method' and the bottom being the 'redirect-source' method. To prove this theory, the timing speaks for itself:

    arg1 for foo=FOOVALUE
     real 0m0.011s user 0m0.004s sys 0m0.008s  # <--time spent in foo
     real 0m0.000s user 0m0.000s sys 0m0.000s  # <--time spent in bar
    arg1 for bar=BARVALUE
    ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
    arg1 for foo=FOOVALUE
     real 0m0.010s user 0m0.004s sys 0m0.004s
     real 0m0.000s user 0m0.000s sys 0m0.000s
    arg1 for bar=BARVALUE
    ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
    arg1 for foo=FOOVALUE
     real 0m0.011s user 0m0.000s sys 0m0.012s
     real 0m0.000s user 0m0.000s sys 0m0.000s
    arg1 for bar=BARVALUE
    ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
    arg1 for foo=FOOVALUE
     real 0m0.012s user 0m0.004s sys 0m0.004s
     real 0m0.000s user 0m0.000s sys 0m0.000s
    arg1 for bar=BARVALUE
    ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
    arg1 for foo=FOOVALUE
     real 0m0.010s user 0m0.008s sys 0m0.004s
     real 0m0.000s user 0m0.000s sys 0m0.000s
    arg1 for bar=BARVALUE
    

    This is the bottom part of about 200 results, done at random intervals. It seems that function creation/destruction takes more time than redirection. Hopefully this will help future visitors to this question (didn't want to keep it to myself).

提交回复
热议问题