Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell variable is available on command line but not in script

Tags:

bash

unix

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?

like image 499
Jaelebi Avatar asked May 02 '09 22:05

Jaelebi


2 Answers

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.

like image 93
Richard Avatar answered Sep 30 '22 20:09

Richard


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
like image 31
David Z Avatar answered Sep 30 '22 20:09

David Z