16

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?

that other guy
  • 116,971
  • 11
  • 170
  • 194
Jaelebi
  • 5,879
  • 8
  • 32
  • 34

4 Answers4

23

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.

NeonGlow
  • 1,659
  • 4
  • 18
  • 36
Richard
  • 10,122
  • 10
  • 42
  • 61
10

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
that other guy
  • 116,971
  • 11
  • 170
  • 194
David Z
  • 128,184
  • 27
  • 255
  • 279
  • 1
    use export var also in your bash profile - if you want your scripts to access these variable. for example JAVA_HOME – LukeSolar Oct 17 '13 at 10:00
  • This is misleading. The `export` has no visible effect on the current shell. It is useful when the value of the variable needs to be made visible to subprocesses started from the current shell. – tripleee Nov 28 '17 at 12:30
  • @tripleee Indeed, and unless I'm missing something, that's exactly what the question is asking about: how to access a variable from a subprocess (which is executing a shell script). – David Z Nov 28 '17 at 21:04
7

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

pixelbeat
  • 30,615
  • 9
  • 51
  • 60
2

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.

digijock
  • 97
  • 2
  • 4