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

时间:2017-07-21 18:41:08

标签: bash heredoc su

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

su - User << EOF

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

EOF

我的目标是在EOF分隔符之间执行代码,就像我实际以用户身份登录一样。

中间线应该安装Homebrew。如果我以用户身份登录并自行运行中间行,则安装正常。但是运行上面的完整脚本会给我带来问题:

-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)'

我尝试过不同的命令,而不仅仅是Homebrew安装,但大部分时间都有问题。在我尝试将命令传递给'su'和实际以该用户身份运行命令之间有什么区别?

1 个答案:

答案 0 :(得分:0)

发生的事情是,嵌入式$(...)命令在 here-document传递给su之前执行。也就是说,传递给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
...

等等。换句话说,$(...)的输出已插入到here-document。

为避免这种情况,您需要转义$

su - User << EOF

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

EOF

或者,您可以通过将起始EOF括在双引号中来告诉shell在没有任何插值的情况下直接处理整个here-document:

su - User << "EOF"

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

EOF