Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 在Bash中从另一个用户范围访问变量_Linux_Bash_Variables_Scope_Su - Fatal编程技术网

Linux 在Bash中从另一个用户范围访问变量

Linux 在Bash中从另一个用户范围访问变量,linux,bash,variables,scope,su,Linux,Bash,Variables,Scope,Su,我在使用以下bash脚本时遇到问题: #!/bin/bash myPassword="foobar" su - postgres <<-'EOF' echo $myPassword # nil EOF echo $myPassword # foobar #/bin/bash myPassword=“foobar” su-postgres您可能需要转义\$mypassword,以便在调用su 此外,您还可以将-c传递到su,以便将某些内容从环境传递到生成的shell:

我在使用以下bash脚本时遇到问题:

#!/bin/bash

myPassword="foobar"

su - postgres <<-'EOF'
    echo $myPassword # nil
EOF

echo $myPassword # foobar
#/bin/bash
myPassword=“foobar”

su-postgres您可能需要转义
\$mypassword
,以便在调用
su

此外,您还可以将
-c
传递到
su
,以便将某些内容从环境传递到生成的shell:

user1:~$ X=foo su -c "bash -c \"whoami && echo \$X\"" user2
Password: 
user2
foo

您正在对herdeoc标记使用
'EOF'
。因此,没有替代发生。如果要在块内进行变量替换,请删除其周围的引号。看

您也可以保留您所拥有的,但使用
su
-p
(或
-m
--preserve environment
)选项可能更适合您


(我确信没有必要提醒您,在脚本中保存密码是不安全的。并且可以使用足够的权限检查进程的环境,因此它也不是一个放置密码的好地方。)

此su命令应该可以工作:

myPassword="foobar"
su postgress -c "echo $myPassword"

谢谢你,我最后删除了引号,效果非常好