bash Shell 变量在命令行中可用,但在脚本中不可用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/815742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:08:41  来源:igfitidea点击:

Shell variable is available on command line but not in script

bashunix

提问by Jaelebi

In the bash command line, I set a variable myPath=/home/user/dir. I created a script in which I put echo $myPathbut it doesnt seem to work. It echoes nothing. If I write echo $myPathin the command line, it works, but not in the script.

在 bash 命令行中,我设置了一个变量myPath=/home/user/dir. 我创建了一个脚本,echo $myPath但它似乎不起作用。它没有回声。如果我echo $myPath在命令行中编写,它可以工作,但不能在脚本中使用。

What can I do to access the myPathvariable in the script?

如何访问myPath脚本中的变量?

采纳答案by David Z

Export the variable:

导出变量:

export myPath=/home/user/dir

This instructs the shell to make the variable available in external processes and scripts. If you don't exportthe variable, it will be considered local to the current shell.

这会指示 shell 使变量在外部进程和脚本中可用。如果您不使用export该变量,它将被视为当前 shell 的本地变量。

To see a list of currently exported variables, use env. This can also be used to verify that a variable is correctly defined and exported:

要查看当前导出的变量列表,请使用env. 这也可用于验证变量是否已正确定义和导出:

$ env | grep myPath
myPath=/home/user/dir

回答by Richard

how did you assign the variable? it should have been:

你是如何分配变量的?它应该是:

$ export myPath="/home/user/dir"

then inside a shell program like:

然后在shell程序中,如:

#!/usr/bin/env bash
echo $myPath

you'll get the desired results.

你会得到想要的结果。

回答by pixelbeat

You could also do this to set the myPath variable just for myscript

您也可以这样做来为 myscript 设置 myPath 变量

myPath="whatever" ./myscript

For details of the admitted tricky syntax for environment variables see: http://www.pixelbeat.org/docs/env.html

有关环境变量公认的棘手语法的详细信息,请参阅:http: //www.pixelbeat.org/docs/env.html

回答by digijock

You must declare your variable assignment with "export" as such:

您必须使用“export”声明变量赋值,如下所示:

export myPath="/home/user/dir"

This will cause the shell to include the variable in the environment of subprocesses it launches. By default, variables you declare (without "export") are not passed to a subprocess. That is why you did not initially get the result you expected.

这将导致 shell 将变量包含在它启动的子进程的环境中。 默认情况下,您声明的变量(没有“导出”)不会传递给 subprocess。这就是您最初没有得到预期结果的原因。