Shell variable is available on command line but not in script

眉间皱痕 提交于 2020-01-31 06:49:49

问题


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. If I write echo $myPath in the command line, it works, but not in the script.

What can I do to access the myPath variable in the script?


回答1:


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 export the variable, it will be considered local to the current 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 | grep myPath
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:

#!/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="whatever" ./myscript

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




回答4:


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

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.



来源:https://stackoverflow.com/questions/815742/shell-variable-is-available-on-command-line-but-not-in-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!