简体   繁体   English

在bash脚本中将变量传递给su命令

[英]passing a variable it to su command in bash script

I need to issue a command from a eg root to user zimbra. 我需要从例如root向用户zimbra发出命令。 The problem is that I also need to set an env variable and some other variables. 问题是我还需要设置一个env变量和其他一些变量。

From a command line I do it like this (that's command used for creating a mailbox in Zimbra): 在命令行中,我这样做(在Zimbra中用于创建邮箱的命令)是这样的:

su - zimbra -c 'export LC_ALL=nb_NO.UTF-8 && p="user.name" && domain="@example.com" && displayname="User Name" && givenname="User" && /opt/zimbra/bin/zmprov ca $p$domain "" cn "$displayname" displayName "$displayname" givenName "$givenname" zimbraPrefFromDisplay "$displayname"'

It works fine. 工作正常。 The problem occurs when I try to automate the process in bash script. 当我尝试自动执行bash脚本中的过程时,会出现问题。 I can't (or don't know how to) pass a variable generated inside script to su command. 我无法(或不知道如何)将脚本内部生成的变量传递给su命令。

#!/bin/bash
var="something";
su - zimbra -c 'export LC_ALL=nb_NO.UTF-8 && echo $var'

When I use script above it doesn't work because $var is declared for root user, not for zimbra user. 当我在上面使用脚本时,它不起作用,因为$ var是为root用户而不是zimbra用户声明的。 Is there a way to to baypass this? 有什么办法可以绕过这个吗?

I've tried to bypass this by generating a string first: 我尝试通过首先生成一个字符串来绕过此操作:

#!/bin/bash
var="something";
string="'export LC_ALL=nb_NO.UTF-8 && echo $var'";
su - zimbra -c $string

but when I do this I get 但是当我这样做时

LC_ALL=nb_NO.UTF-8: -c: line 0: unexpected EOF while looking for matching `'' LC_ALL=nb_NO.UTF-8: -c: line 1: syntax error: unexpected end of file LC_ALL = nb_NO.UTF-8:-c:行0:寻找匹配的EOF时出现意外的EOF LC_ALL = nb_NO.UTF-8:-c:行1:语法错误:文件意外结束

Any help? 有什么帮助吗?

Unfortunately none of the above comments ideas worked for me. 不幸的是,以上评论都对我没有帮助。 I wound up puzzling out that I could do the following. 我不知所措,我可以做以下事情。 Escaping the double-quotes and wrapping in actual double-quotes seems absolutely necessary, plus pipe to xargs allowed the realized variable to be passed through. 转义双引号并包装在实际的双引号中似乎是绝对必要的,再加上xargs的管道,可以传递实现的变量。

echo "\\"/web/jboss-eap-7.1/bin/domain.sh -Djboss.domain.base.dir=$NODE/\\ &\\"" | xargs su - jboss -c

Hope this answer helps others! 希望这个答案对别人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM