Shell variable is available on command line but not in script

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

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.


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

Tags:

Unix

Bash