0

I went through a shell scripting tutorial explaining about global variables (export). I encountered a do-it-yourself example to illustrate the concept of global variables in shell scripting, and I tried it by:

$ cat trial

vech=Bus
echo $vech
/bin/bash
echo "before empty line"
echo $vech
echo "after empty line"
vech=Car
echo $vech
exit
echo $vech

The expected output for this program was:

Bus
before empty line 
after empty line
Car
Bus

But I got :

$ chmod 777 trial
$ ./trial
Bus
$ 

where I am getting wrong?, I am new this flavor please help me.

3
  • 1
    That looks like a set of commands which you should be entering on the terminal, not run as a script. The second echo and everything up to the exit are meant to be commands to /bin/bash.
    – muru
    Dec 5, 2014 at 17:01
  • thanx @muru ,well by using /bin/sh it provides me with prompt $,,but not with /bin/bash??
    – lazarus
    Dec 5, 2014 at 17:27
  • What @muru means is that /bin/bash does not receive the lines after it as input. You could replace it with sleep 1 and the script would not be much different (except now you have to explicitly exit from Bash before the script will continue).
    – tripleee
    Dec 10, 2014 at 8:39

1 Answer 1

1

Try doing this using a here-document :

vech=Bus
echo $vech
/bin/bash<<EOF
echo "before empty line"
echo $vech
echo "after empty line"
vech=Car
echo $vech
exit
EOF
echo $vech
2
  • thanx@sputnick ,,but this program has changed the essence of globlal variable explanation,,because it prints::anupam@JAZZ:~/Desktop$ chmod +x trial_ask_ubuntu anupam@JAZZ:~/Desktop$ ./trial_ask_ubuntu Bus before empty line Bus after empty line Bus Bus anupam@JAZZ:~/Desktop$
    – lazarus
    Dec 5, 2014 at 17:43
  • The contents of the here document are evaluated before they are passed to the subshell. Use single quotes in <<'EOF' to prevent that. However, you will need to export vech if you want it to be defined in the subshell.
    – tripleee
    Dec 10, 2014 at 8:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .