使用此处文档以另一个用户身份运行脚本中的命令

squ*_*rjn 5 bash heredoc su

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

su - User << EOF

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

EOF
Run Code Online (Sandbox Code Playgroud)

我的目标是执行 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)'
Run Code Online (Sandbox Code Playgroud)

我尝试过不同的命令,而不仅仅是 Homebrew 安装,但大多数时候都会遇到问题。我尝试将命令传递给“su”与以该用户身份实际运行命令之间有什么区别?

Sto*_*ica 5

发生的情况是,嵌入的$(...)命令此处文档传递到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
...
Run Code Online (Sandbox Code Playgroud)

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

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

su - User << EOF

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

EOF
Run Code Online (Sandbox Code Playgroud)

EOF或者,您可以通过将开头括在双引号内,告诉 shell 按字面意思处理整个此处文档,而不进行任何插值:

su - User << "EOF"

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

EOF
Run Code Online (Sandbox Code Playgroud)