代码之家  ›  专栏  ›  技术社区  ›  squarjn

作为另一个用户使用here doc在脚本中运行命令

  •  4
  • squarjn  · 技术社区  · 9 年前

    我希望能够在脚本中间切换用户。这里有一个尝试:

    su - User << EOF
    
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" </dev/null
    
    EOF
    

    中间线路应该安装自制软件。如果我以用户身份登录并独立运行中间行,它安装得很好。但是运行上面的完整脚本会给我带来问题:

    -e:5: unknown regexp options - lcal
    -e:6: unknown regexp options - lcal
    -e:8: unknown regexp options - Cach
    -e:9: syntax error, unexpected tLABEL
    BREW_REPO = https://github.com/Homebrew/brew.freeze
                      ^
    -e:9: unknown regexp options - gthb
    -e:10: syntax error, unexpected tLABEL
    CORE_TAP_REPO = https://github.com/Homebrew/homebrew-core.freeze
                          ^
    -e:10: unknown regexp options - gthb
    -e:32: syntax error, unexpected end-of-input, expecting keyword_end
    -bash: line 34: end: command not found
    -bash: line 36: def: command not found
    -bash: line 37: escape: command not found
    -bash: line 38: end: command not found
    -bash: line 40: syntax error near unexpected token `('
    -bash: line 40: `  def escape(n)'
    

    我尝试了不同的命令,而不是仅仅安装自制软件,但大多数时候都有问题。在我尝试向“su”传递命令和作为该用户实际运行命令之间有什么区别?

    1 回复  |  直到 9 年前
        1
  •  4
  •   janos slartidan    9 年前

    $(...) 执行命令 之前 此处文档传递给 su 也就是说

    /usr/bin/ruby -e "#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby
    # This script installs to /usr/local only. To install elsewhere you can just
    # untar https://github.com/Homebrew/brew/tarball/master anywhere you like or
    # change the value of HOMEBREW_PREFIX.
    HOMEBREW_PREFIX = "/usr/local".freeze
    HOMEBREW_REPOSITORY = "/usr/local/Homebrew".freeze
    HOMEBREW_CACHE = "#{ENV["HOME"]}/Library/Caches/Homebrew".freeze
    ...
    

    等等。换句话说,输出 $(...) 已插入此处文档。

    为了避免这种情况,你需要逃离 $ :

    su - User << EOF
    
    /usr/bin/ruby -e "\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" </dev/null
    
    EOF
    

    或者,您可以告诉shell,通过封闭起始值,不进行任何插值,直接处理整个here文档 EOF

    su - User << "EOF"
    
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" </dev/null
    
    EOF
    
    推荐文章