Shell Scripts Part 2

Click to rate this tutorial!
[Total: 0 Average: 0]

Create a small shell script, testVar2.sh:
testVar2.sh

#!/bin/sh
echo “testVar is: $testVar”
testVar=”my shell script”
echo “testVar is: $testVar”

Now run the script:

$ ./testVar2.sh
testVar is:
testVar is: my shell script

testVar hasn’t been set to any value, so it’s blank. Then we give it a value, and it has the expected result.
Now run:

$ testVar=hello
$ ./testVar2.sh
testVar is:
testVar is: my shell script

It’s still not been set! What’s going on?!
When you call testVar2.sh from your interactive shell, a new shell is spawned to run the script. This is partly because of the #!/bin/sh line at the start of the script, which we discussed earlier.
We need to export the variable for it to be inherited by another program – including a shell script. Type:

$ export testVar
$ ./testVar2.sh
testVar is: hello
testVar is: my shell script

Now look at line 3 of the script: this is changing the value of testVar. But there is no way that this will be passed back to your interactive shell. Try reading the value of testVar:

$ echo $testVar
hello
$

Once the shell script exits, its environment is destroyed. But testVar keeps its value of hello within your interactive shell.
In order to receive environment changes back from the script, we must source the script – this effectively runs the script within our own interactive shell, instead of spawning another shell to run it.
We can source a script via the “.” command:

$ testVar=hello
$ echo $testVar
hello
$ . ./testVar2.sh
testVar is: hello
testVar is: my shell script
$ echo $testVar
my shell script

To be continued….

Click to rate this tutorial!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published.