为什么像 [ $var == 'str' ] 这样的 zsh 代码作为命令运行良好,但作为脚本文件却出错? [英] Why the zsh codes like [ $var == 'str' ] runs well as a command but error as a script file?

查看:22
本文介绍了为什么像 [ $var == 'str' ] 这样的 zsh 代码作为命令运行良好,但作为脚本文件却出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

zsh_test.sh很简单,如下:

#!/usr/bin/env zsh

if [ $USER == 'root' ]; then
    echo "root"
else
    echo "not root"
fi

  • 将以上代码复制粘贴到zsh shell中,运行良好.

    • Copy and paste the above codes into a zsh shell, it executed well.

      $ #!/usr/bin/env zsh
      $ if [ $USER == 'root' ]; then
      then>     echo "root"
      then> else
      else>     echo "not root"
      else> fi                     
      not root
      

    • 但是直接执行脚本文件zsh_test.sh,报错.

      $ ./zsh_test.sh
      ./zsh_test.sh:3: = not found
      

    • 推荐答案

      我现在明白出了什么问题:您是一个相当晦涩的 zsh 机制的受害者,该机制在 zshexpn 手册页和称为'='扩展.来自手册页:

      I now see what's wrong: You are the victim of a fairly obscure zsh mechanism, which is described in the zshexpn man page and is called '=' expansion. From the man-page:

      如果一个单词以不带引号的 `=' 开头并且设置了 EQUALS 选项,则该单词的其余部分将作为命令的名称.如果该名称存在命令,则该单词将替换为该命令的完整路径名.

      If a word begins with an unquoted `=' and the EQUALS option is set, the remainder of the word is taken as the name of a command. If a command exists by that name, the word is replaced by the full pathname of the command.

      你可以用命令试试

      echo ==
      

      也输出此错误消息.例如,在我的平台上

      which also outputs this error message. For instance, on my platofm

      echo =ruby
      

      输出 /usr/bin/ruby,因为这是我安装 ruby​​ 的地方.如果您的 PATH 中有一个名为 = 的程序,则 == 将解析为该路径.

      outputs /usr/bin/ruby, because this is where I have ruby installed. If you would have in your PATH a program named =, the == would resolve to this path.

      虽然在 [ ... ] 中使用双 == 符号是不常见的,但此命令的 zsh 实现允许这样做,但您必须引用运算符,以避免 =-展开:

      While it is unusual to use a double == sign inside [ ... ], the zsh implementation of this command allows it, but you would have to quote the operator, to avoid =-expansion:

      if [ $USER '==' root ]; then
      

      另一种方法是使用 [[ ... ]] 代替.这不是一个命令,而是一个句法结构,它内部的扩展规则是不同的.因此

      An alternative would be to use [[ ... ]] instead. This is not a command, but a syntactic construct, and expansion rules are different inside it. Therefore

      if [[ $USER == root ]]; then
      

      也可以.

      这篇关于为什么像 [ $var == 'str' ] 这样的 zsh 代码作为命令运行良好,但作为脚本文件却出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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