Viky
Viky

Reputation: 405

Value of global variable doesn't change in BASH

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.

Upvotes: 1

Views: 12547

Answers (3)

anon
anon

Reputation:

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.

Upvotes: 2

dsm
dsm

Reputation: 10393

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:~]$ 

Upvotes: 0

innaM
innaM

Reputation: 47829

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

Upvotes: 1

Related Questions