Saturday, December 8, 2018

Persistent Variable by sourcing in shell scripting

With #!/bin/sh in the shell script, it invokes other shell and executes the script from there. So even if the variable values is set, it won't reflect in the script running.

Instead export the variable so that it will take the variable value while executing the script. Here we need to notice that if the variable value is changed in the script it will only to the particular shell execution, you can verify this by echo'ing the variable.

So as to persist the value, you need to source. We can source a script via the "." (dot) command. Sourcing the script effectively runs the script in the same interactive shell.

Example: 
vi myscript.sh
echo "test var value: $MY_VAR"
MY_VAR=pramod
echo "latest value of var is: $MY_VAR"

Executing:
Case 1: ./myscript.sh
Output:
test var value:
latest value of var is: pramod

Case 2:
MY_VAR=hoy
./myscript.sh
test var value:
latest value of var is: pramod

Case 3:
export MY_VAR=hoy
./myscript.sh
test var value: hoy
latest value of var is: pramod

Now echo'ing the MY_VAR
echo $MY_VAR
hoy

Case 4:
. ./myscript.sh
test var value: hoy
latest value of var is: pramod

Now echo'ing the MY_VAR
echo $MY_VAR
pramod

This implies, the variable is persistent from the script execution.

***

No comments:

Post a Comment