In the bash command line, I set a variable myPath=/home/user/dir . I created a script in which I put echo $myPath but it doesnt seem to work. It echoes nothing. What can I do to access the myPath variable in the script. If I write echo $myPath in the command, it works, but not in the script.
在bash命令行中,我设置了一个变量myPath = / home / user / dir。我创建了一个脚本,我在其中放置了echo $ myPath,但它似乎没有用。它没有回音。如何在脚本中访问myPath变量。如果我在命令中编写echo $ myPath,它可以工作,但不在脚本中。
4 个解决方案
#1
Try
export myPath=/home/user/dir
#2
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.
你会得到想要的结果。
#3
You could also do this to set the myPath variable just for myscript
您也可以这样设置myPath变量仅用于myscript
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
#4
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将变量包含在它启动的子进程的环境中。默认情况下,您声明的变量(没有“export”)不会传递给子流程。这就是为什么你最初没有得到你期望的结果。
#1
Try
export myPath=/home/user/dir
#2
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.
你会得到想要的结果。
#3
You could also do this to set the myPath variable just for myscript
您也可以这样设置myPath变量仅用于myscript
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
#4
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将变量包含在它启动的子进程的环境中。默认情况下,您声明的变量(没有“export”)不会传递给子流程。这就是为什么你最初没有得到你期望的结果。