Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.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 在shell中作为另一个用户运行时无法初始化变量_Linux_Bash_Shell_Variables_Scope - Fatal编程技术网

Linux 在shell中作为另一个用户运行时无法初始化变量

Linux 在shell中作为另一个用户运行时无法初始化变量,linux,bash,shell,variables,scope,Linux,Bash,Shell,Variables,Scope,我正在运行一个shell脚本,它将作为不同的用户执行一些工作(脚本如下所示)。当作为另一个用户运行时,我能够访问脚本中声明的变量。在用户范围内分配的变量未初始化 #!/bin/bash presentdir="$(pwd)" sudo -H -u user1 bash <<EOF echo "$presentdir" #its is printing the value on console EOF #/bin/bash presentdir=“$(pwd)” sudo-H-u u

我正在运行一个shell脚本,它将作为不同的用户执行一些工作(脚本如下所示)。当作为另一个用户运行时,我能够访问脚本中声明的变量。在用户范围内分配的变量未初始化

#!/bin/bash
presentdir="$(pwd)"
sudo -H -u user1 bash <<EOF
echo "$presentdir"
#its is printing the value on console
EOF
#/bin/bash
presentdir=“$(pwd)”

sudo-H-u user1 bash
$variable
$(command)
在执行使用here文档的命令之前都在here文档内部展开

在第二种情况下,传递给作为
user1
运行的
bash
的字符串实际上是

presentdir="working directory before running sudo -H"
echo ""

您可以在here文档中使用
\$
转义
$
,以修复脚本。您可以将
sudo-H-u user1 bash
替换为
cat
,以打印将要传递的字符串。

扩展发生在原始用户端,而不是sudo之后的端

sudo -H -u user1 bash <<EOF
presentdir="$(pwd)"
echo "$presentdir"
EOF
将打印
$(pwd)
sudo-u user1
之后运行的输出

或双引号引用变量:

sudo -H -u user1 bash <<EOF
presentdir="\"\$(pwd)\""
echo "\"\$presentdir\""
EOF

这将使herdoc不会在原始用户端展开(小而有用的技巧)。

您确定
\“
吗?将
sudo…bash
替换为
cat
,以查看结果字符串。我有一个快速问题
pre\u dir=$(dirname“$0”)sudo-u user1 bash@S.Harish导出
pre\u dir
或使用
EOF
而不是
“EOF”
presentdir="working directory before running sudo -H"
echo ""
sudo -H -u user1 bash <<EOF
presentdir="$(pwd)"
echo "$presentdir"
EOF
sudo -H -u user1 bash <<EOF
presentdir="/home/orinal_user"
echo ""
EOF
sudo -H -u user1 bash -c 'presentdir="$(pwd)"; echo "$presentdir"'
sudo -H -u user1 bash <<EOF
presentdir="\"\$(pwd)\""
echo "\"\$presentdir\""
EOF
sudo -H -u user1 bash <<"EOF"
presentdir="$(pwd)"
echo "$presentdir"
EOF