【问题标题】:Accessing variables from another user scope in Bash在 Bash 中从另一个用户范围访问变量
【发布时间】:2014-05-25 16:01:07
【问题描述】:
我在使用以下 bash 脚本时遇到问题:
#!/bin/bash
myPassword="foobar"
su - postgres <<-'EOF'
echo $myPassword # nil
EOF
echo $myPassword # foobar
如何从postgres 用户会话中访问或管道$myPassword 的内容?
在有和没有export 的情况下都试过了,但没有运气。
【问题讨论】:
标签:
linux
bash
variables
scope
su
【解决方案1】:
您使用'EOF' 作为heredoc 标记。所以不会发生替换。如果要在块内进行变量替换,请删除其周围的引号。见Heredocs And Herestrings。
您也可以保留现有的东西,但使用su 的-p(或-m 或--preserve-environment)选项可能更适合您。
(我确信没有必要提醒您将密码保存在脚本中是不安全的。并且可以使用足够的权限检查进程的环境,因此它也不是密码的好地方。)
【解决方案2】:
您可能需要转义 \$mypassword 以便在调用 su 之前它不会在原始脚本中得到解决
此外,您可以将-c 传递给su,以便将环境中的某些内容传递给生成的shell:
user1:~$ X=foo su -c "bash -c \"whoami && echo \$X\"" user2
Password:
user2
foo
【解决方案3】:
这个 su 命令应该可以工作:
myPassword="foobar"
su postgress -c "echo $myPassword"