1

I have a shell script that sets a variable. I can access it inside the script, but I can't outside of it. Is it possible to make the variable global?

Accessing the variable before it's created returns nothing, as expected:

$ echo $mac

$

Creating the script to create the variable:

#!/bin/bash
mac=$(cat \/sys\/class\/net\/eth0\/address)
echo $mac
exit 0

Running the script gives the current mac address, as expected:

$ ./mac.sh
12:34:56:ab:cd:ef
$ 

Accessing the variable after its created returns nothing, NOT expected:

$ echo $mac

$

Is there a way I can access this variable at the command line and in other scripts?

2
  • 2
    Interesting use of the word "global". If you want to make data available to all processes on the host, the natural solution is to write that data to the filesystem. If you want all processes on the host to share the same memory space, you seek chaos. Commented Dec 25, 2019 at 9:12
  • Maybe you want to make it an environment variable? I could write an answer if you want details. Commented Dec 25, 2019 at 17:04

1 Answer 1

3

A child process can't affect the parent process like that.

You have to use the . (dot) command — or, if you like C shell notations, the source command — to read the script (hence . script or source script):

. ./mac.sh
source ./mac.sh

Or you generate the assignment on standard output and use eval $(script) to set the variable:

$ cat mac.sh
#!/bin/bash
echo mac=$(cat /sys/class/net/eth0/address)
$ bash mac.sh
mac=12:34:56:ab:cd:ef
$ eval $(bash mac.sh)
$ echo $mac
12:34:56:ab:cd:ef
$

Note that if you use no slashes in specifying the script for the dot or source command, then the shell searches for the script in the directories listed in $PATH. The script does not have to be executable; readable is sufficient (and being read-only is beneficial in that you can't run the script accidentally).

It's not clear what all the backslashes in the pathname were supposed to do other than confuse; they're unnecessary.

See ssh-agent for precedent in generating a script like that.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I removed the backslashes. I tried your above script, and I could follow along with the first part, but when I run $(bash mac.sh) I get -bash: mac=12:34:56:ab:cd:ef: command not found, and after that then I still get a blank response for echo $mac.
I've updated my answer, @GFL, fixing my mistake (added the eval — but be careful; eval can be dangerous). I've also noted ssh-agent as precedent for what I suggest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.