BASH:如何参数传递给一个别名:不能使用功能 - 巴什条件句的语法 [英] BASH: how to pass in arguments to an alias: CANNOT USE A FUNCTION - syntax of Bash conditionals

查看:100
本文介绍了BASH:如何参数传递给一个别名:不能使用功能 - 巴什条件句的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的不同在于经典的使用功能的答案是行不通的。添加了一张字条给现有的别名问题是相当于发送一个建议,E-mail给雅虎。

This question differs in that the classic "use a function" answer WILL NOT work. Adding a note to an existing Alias question is equivalent to sending a suggestion e-mail to Yahoo.

我想写宏绕过BASH的可怕IF语法。要知道,[[[,((... BASH:流量控制的PHP ...添加另一架我仍然在等待(((((((的形式不太清楚。为什么BASH没有重新调整(,在IF语句(有没有真正的语义。

I am trying to write macros to get around BASH's horrendous IF syntax. You know, the [, [[, ((...BASH: the PHP of flow control...just add another bracket. I'm still waiting for the "(((((((" form. Not quite sure why BASH didn't repurpose "(", as "(" has no real semantics at the if statement.

的想法是有命名为别名[[[和((,因为这些durned测试十岁上下的功能,每个人心中都有一个令人沮丧的不同的语法。老实说,我从来不记得哪个是哪个(你怎么可以这样?这是完全专案!),好运试图谷歌[[。

The idea is to have named aliases for [, [[ and (( , as each one of these durned test-ish functions has a frustratingly different syntax. I honestly can never remember which is which (how COULD you? It's completely ad hoc!), and good luck trying to google "[[".

然后,我会使用的名称为助记符,以及别名摆脱的间距要求完全可怕的差异。例如:whatdoyoucallthisIf搜索((,工作人员健康保险(壳IF),mysterydoublesquarebacketif对于这似乎主要是做同样的事情,那可怕的[[东西[,只是它没有

I would then use the names as a mnemonic, and the alias to get rid of the completely awful differences in spacing requirements. Examples: "whatdoyoucallthisIf" for "((", "shif" (for shell if), "mysterydoublesquarebacketif" for that awful [[ thing which seems to mostly do the same thing as [, only it doesn't.

因此​​,我的必须的有形式的东西:

Thus, I MUST have something of the form:

别名IFREPLACEMENT =如果[\\ $ @;然后将

alias IFREPLACEMENT="if [ \$@ ]; then"

但显然不是\\ $ @,而只想水泥在当前的参数列表运行别名的外壳。

But obviously not \$@, which would just cement in the current argument list to the shell running the alias.

功能将在这种情况下工作,该功能:

Functions will not work in this case, as the function:

function IFREPLACEMENT {
    if [ $@ ]; then
}

是非法的。

在CSH,你可以说
    别名ABC等等等等!*
!1等是否有BASH任何类似(不,!*在BASH不工作)?

In CSH, you could say alias abc blah blah !* !1, etc. Is there ANYTHING in BASH that is similar (no, !* doesn't work in BASH)?

或者是[我只是运气不好]; ?

Or am [ "I just out of luck" ]; ?

顺便说一句,这里有一些涉及BASH,我尽量避免使用良好定义的别名测试十岁上下的功能令人沮丧的差异,人们将不得不使用,而不是选错了[[, [或((

As an aside, here are some of the frustrating differences involving test-ish functions in BASH that I am trying to avoid by using well-defined aliases that people would have to use instead of picking the wrong "[[", "[" or "((":


  • ((实在是让人毛骨悚然......如果一个变量包含另一个变量的名称,它derferenced尽可能多的水平需要)

  • ((不需要空间,如'['和'['

  • ((不需要$为要取消引用变量

  • [的-gt是数字或死亡。 [似乎有武断的限制。

  • '['和'['使用>(ETC)词法比较运营商,但它们有不同的令人沮丧的规则,使它看起来像他们正在做的数字比较,当他们真的不是。

  • 为一个变量:A =(空值),[$ A == 123]是一个语法错误,但((A == 123))不是

推荐答案

更新:基于@konsolebox反馈,建议,现在是的总是的使用 [...] 为简单性和性能(推荐使用((...))数值原来的接听/布尔测试)。

Update: Based on feedback from @konsolebox, the recommendation is now to always use [[...]] for both simplicity and performance (the original answer recommended ((...)) for numerical/Boolean tests).

@Oliver查尔斯沃思,在关于这个问题的评论,使得的试图隐藏底层庆典语法<的情况下/ STRONG> - 我同意

@Oliver Charlesworth, in a comment on the question, makes the case for not trying to hide the underlying bash syntax - and I agree.

您可以简化事情有以下的规则


  • 始终使用 [...] 做检查。

    • 仅使用 [...] 如果POSIX相容性是必须的。如果可用, [...] 始终是更好的选择(更少的惊喜,更多的功能和几乎快一倍 [1] )。

    • 使用双引号的, $ - prefixed变量引用 - 稳健性和简单性(你付出了轻微的性能损失双引号,虽然 1 ) - 例如,$ VAR;看到重新例外的RHS == =〜之下。

    • Always use [[ ... ]] for tests.
      • Only use [ ... ] if POSIX compatibility is a must. If available, [[ ... ]] is always the better choice (fewer surprises, more features, and almost twice as fast[1]).
      • Use double-quoted, $-prefixed variable references - for robustness and simplicity (you do pay a slight performance penalty for double-quoting, though1) - e.g., "$var"; see the exceptions re the RHS of == and =~ below.

      • 始终把空间的初始分隔符之后和条件的关闭定界符之前(不管是 [ / ( (]] / ))

      • 从来没有把周围 = 空格变量分配即可。

      • ALWAYS put a space after the initial delimiter and before the closing delimiter of conditionals (whether [[ / (( or ]] / )))
      • NEVER put spaces around = in variable assignments.

      这些规则更为严格比他们需要 - 在简化的利益

      These rules are more restrictive than they need to be - in the interest of simplification.

      技巧和陷阱


      • 请注意, 数字的比较[[...]] ,你必须使用 -eq -gt -ge -lt -le ,因为 == &LT; &LT; = &GT; &GT; = 词汇的比较。

        • [110 -gt 2]和放大器;&安培;回声是

        • Note that for numeric comparison with [[ ... ]], you must use -eq, -gt, -ge, -lt, -le, because ==, <, <=, >, >= are for lexical comparison.
          • [[ 110 -gt 2 ]] && echo YES

          • ['ABC'=='一'*]]&放大器;&安培;回声是

          • [[ 'abc' == 'a'* ]] && echo YES

          • ['ABC'=〜^'A'+ $]]&功放;&安培;回声是

          • 重新='^ A + $'; ['ABC'=〜$重新]&放大器;&安培;回声YES#*不带引号的*使用变种。 $重新

          • [[ 'abc' =~ ^'a'.+$ ]] && echo YES
          • re='^a.+$'; [[ 'abc' =~ $re ]] && echo YES # *unquoted* use of var. $re

          替代 [...] ,纯数字/布尔测试,是使用算术评估,((...)) ,其性能堪比 [(约慢15-20% 1 );算术评估(见男人庆典节算术评估

          An alternative to [[ ... ]], for purely numerical/Boolean tests, is to use arithmetic evaluation, ((...)), whose performance is comparable to [[ (about 15-20% slower1); arithmetic evaluation (see section ARITHMETIC EVALUATION in man bash):


          • 允许C风格的运算(整数),如 + 操作 - * / ** ...

          • 支持任务,包括递增和递减操作( ++ / - )。

          • 没有 $ preFIX所需的变量引用。

          • Allows C-style arithmetic (integer) operations such as +, -, *, /, **, %, ...
          • Supports assignments, including increment and decrement operations (++ / --).
          • No $ prefix required for variable references.


          • 买者的:你仍然需要在 $ 2的情景:

            • 如果您想要的指定基数执行前期参数扩展的,如删除preFIX:

              • VAR = 010; ((10#$ VAR&GT; 9))及和放大器;回声YES#任务基数10

              • VAR = V10; (($ {VAR#V}&GT; 9))及和放大器;回声YES#条初始的V

              • Caveat: You still need the $ in 2 scenarios:
                • If you want to specify a number base or perform up-front parameter expansion, such as removing a prefix:
                  • var=010; (( 10#$var > 9 )) && echo YES # mandate number base 10
                  • var=v10; (( ${var#v} > 9 )) && echo YES # strip initial 'v'

                  • ((...),奇怪的是,扩展的变量名而不 $ 递归,直到它的值是现有变量的不是这个名字了:

                  • VAR1 = 10; VAR2 = VAR1; ((VAR2&GT; 9))及&放大器;回声是

                  • VAR2 扩展到 10 (!)

                  • ((...), curiously, expands a variable name without $ recursively, until its value is not the name of an existing variable anymore:
                  • var1=10; var2=var1; (( var2 > 9 )) && echo YES
                  • var2 expands to 10(!)

                  有laxer空白规则。

                  Has laxer whitespace rules.

                  您甚至可以塞进算术EX pressions,包括分配,到 [是基于数值运算符条件语句,尽管这可能会得到更多的混乱;例如:

                  You can even cram arithmetic expressions, including assignments, into [[ conditionals that are based on numeric operators, though that may get even more confusing; e.g.:

                  v1=1 v2=3; [[ v1+=1 -eq --v2 ]] && echo TRUE # -> both $v1 and $v2 == 2
                  


                • 注意:在此背景下,引用我的意思是单或双引号整个字符串,而不是 \\ 在-escaping单个字符一个字符串不括在单或双引号。

                  Note: In this context, by 'quoting' I mean single- or double-quoting an entire string, as opposed to \-escaping individual characters in a string not enclosed in either single- or double quotes.

                  1
                  下面code - 由@konsolebox改编自code - 用于性能测量

                  请注意:


                  • 结果的可以的因平台不同 - 数字基于OS X 10.9.3和Ubuntu 12.04

                  • [正在接近两倍的速度为 [(系数1.9左右),是基于:

                    • 使用的不带引号 $ - prefixed在 [变量引用(使用双引号的变量引用会减慢速度有点)

                    • The results can vary by platform - numbers are based on OS X 10.9.3 and Ubuntu 12.04.
                    • [[ being nearly twice as fast as [ (factor around 1.9) is based on:
                      • using unquoted, $-prefixed variable references in [[ (using double-quoted variable references slows things down somewhat)
                      #!/usr/bin/env bash
                      
                      headers=( 'test' '[' '[[/unquoted' '[[/quoted' '[[/arithmetic' '((' )
                      iterator=$(seq 100000)
                      {
                      time for i in $iterator; do test "$RANDOM" -eq "$RANDOM"; done
                      time for i in $iterator; do [ "$RANDOM" -eq "$RANDOM" ]; done
                      time for i in $iterator; do [[ $RANDOM -eq $RANDOM ]]; done
                      time for i in $iterator; do [[ "$RANDOM" -eq "$RANDOM" ]]; done
                      time for i in $iterator; do [[ RANDOM -eq RANDOM ]]; done
                      time for i in $iterator; do (( RANDOM == RANDOM )); done
                      } 2>&1 | fgrep 'real' | { i=0; while read -r line; do echo "${headers[i++]}: $line"; done; } | sort -bn -k3.3 | awk 'NR==1 { baseTime=substr($3,3) } { time=substr($3,3); printf "%s %s%%\n", $0, (time/baseTime)*100 }' | column -t
                      

                      输出时间从最快到最慢,与pssed为最快时间的百分比慢倍还前$ P $。

                      Outputs times from fastest to slowest, with slower times also expressed as a percentage of the fastest time.

                      这篇关于BASH:如何参数传递给一个别名:不能使用功能 - 巴什条件句的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆