bash - 使用此处的文档作为另一个用户在脚本中运行命令

标签 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”与以该用户身份实际运行命令之间有什么区别?

最佳答案

发生的事情是,嵌入式$(...)命令在 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
...

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

为避免这种情况,您需要避开 $ :
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

关于bash - 使用此处的文档作为另一个用户在脚本中运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45244670/

相关文章:

有选择地终止进程的 Linux 脚本

javascript - 在 JavaScript 中创建多行字符串

在 PHP 生成的 JavaScript 中调用时,通过 heredoc 声明的 PHP 变量将无法正确解析

linux - 从ant通过sshexec将密码传递给 "su"命令

android - 如何在 Android 上执行 "su"?

c - 为什么以不同用户身份运行命令时性能会急剧下降

bash - Hadoop 2.2.0流内存限制

Linux:删除多个文件的文件扩展名

bash - 在 UNIX 中使用 awk 或 sed 进行文本解析。提取端口号

linux - 如何 cat <<EOF >> 包含代码的文件?