Search This Blog

Tuesday, July 09, 2013

setenv does not work from script

This post explains how to export a variable from a shell script to a tcsh parent shell.
 
consider the following script
hogwarts:~/x> cat setup_var.sh
#! /bin/tcsh -f

setenv a RAJU
echo $a
The executable bit is set on the script
hogwarts:~/x> chmod +x setup_var.sh
hogwarts:~/x> ls -al setup_var.sh
-rwxr-xr-x 1 rajulocal rajulocal 39 Jul  9 03:40 setup_var.sh
 
I am using the tcsh shell
hogwarts:~/x> echo $0
tcsh
When executed, it shows that the variable "a" is getting the correct value
hogwarts:~/x> ./setup_var.sh
RAJU
However, the variable is not exported to the parent shell even though setenv is used in the script.
hogwarts:~/x> echo $a
a: Undefined variable.
The solution is to "source the script" instead of "dot executing".
hogwarts:~/x> source setup_var.sh
RAJU
hogwarts:~/x> echo $a
RAJU
Voila! Now the variable "a" is exported to the parent shell.

Happy shell script hacking...

Followers