2017-07-21 24 views
1

我希望能够在脚本中间切换用户。这里有一个尝试:使用here doc在脚本中运行命令

su - User << EOF 

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

EOF 

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

中间线应该安装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)' 

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

+0

难道你不能使用“sudo -u”吗? –

回答

0

发生了什么事情,嵌入式$(...)命令在执行之前这里文档传递给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 

或者,你可以告诉shell硬是把整个here文档没有任何的插值,通过封闭双引号内开始EOF

su - User << "EOF" 

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

EOF