views:

1143

answers:

3

I am working on a BASH script which has a global variable. The value of the variable changes in a function/subroutine. But the value doesnt change when I try to print that variable outside the function. The Sample code is as follows:

#!/bin/bash

count=

linux_f()
    {
        let count=100
    }

linux_f

echo $count

The echo statement prints blank and not 100 Why the value of the global variable doesn't traverse in the function and out.

+1  A: 

Perhaps because you are assigning to countl and not to count?

innaM
@Manni. Sorry for the typo. its the same varaible
Viky
A: 

There is a spelling mistake in that variable assignment (inside the function). Once fixed it will work:

[dsm@localhost:~]$ var=3
[dsm@localhost:~]$ echo $var
3
[dsm@localhost:~]$ function xxx(){ let var=4 ; }
[dsm@localhost:~]$ xxx
[dsm@localhost:~]$ echo $var
4
[dsm@localhost:~]$

And run as a script:

[dsm@localhost:~]$ cat test.sh 
#!/bin/bash

var=
echo "var is '$var'"
function xxx(){ let var=4 ; }
xxx
echo "var is now '$var'"
[dsm@localhost:~]$ ./test.sh #/ <-- #this is to stop the highlighter thinking we have a regexp
var is ''
var is now '4'
[dsm@localhost:~]$
dsm
I have put the code in a script. Can you try in a script. as per my understannding working on script and prompt, the behaviour might be different due to shell and subshell concept.
Viky
Not in this case, but i edited my answer as you asked
dsm
@dsm. Can you let me know what version of bash and linux you using.I am sure this is not working for me. I have Kernel version 2.6.9-67.0.20.ELsmp and bash version is 3.
Viky
@Viky: it doesn't matter... even the most retarded shell will work as expected. Tell me one thing tho, are you expecting to see the variable set *AFTER* your script has run?
dsm
+2  A: 

Your code works for me, printing 100. This is the code I used:

count=

linux_f()
    {
        let count=100
    }

linux_f

echo $count

Edit: I have tried this with version 2 of bash on MSYS and version 3 on Fedora Linux and it works on both. Are you really sure you are executing that script? Try putting an echo "this is it" in there just to make sure that something gets displayed. Other than that, I'm at a loss.

anon
Tried the same thing again. not working for me. Can you tell me what might be wrong. just to clarify, i put the code in a x.sh file and then run with ./x.sh.
Viky
just to add kernel version is 2.6.9-67.0.20.ELsmp and bash version is 3
Viky
Works for me on RedHat AS3 kernel 2.6.9-67.0.15.ELsmp, Bash 3.00.15. Try copying the echo statement into the function, after you set the variable and see if that outputs the correct value.
jon hanson