Help with retaining variable scope


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with retaining variable scope
# 1  
Old 09-16-2011
Lightbulb Help with retaining variable scope

Hi,

I use Korn Shell. Searched Forum and modified the way the file is input to the while loop, but still the variable does not seem to be retaining the final count.

Code:
while read name
        do
                Tmp=`echo $name | awk '{print $9 }'`
                Count=`cat $Tmp | wc -l`
                echo $Count
                Value=`expr $Value + $Count`
                echo "Value is  $Value"
        done < filelist
        echo "Value=$Value"

Code:
$ sh file.sh
329
Value is  329
Value=0

Can anyone please tell me y the value is not retained.
# 2  
Old 09-16-2011
Try:

Code:
./file.sh

When you invoke the script as sh file.sh the shebang line is ignored.
This User Gave Thanks to radoulov For This Post:
# 3  
Old 09-16-2011
Wow!! it works fine..

But im suprised at the fact that my parent shell is a Korn shell too, so even if the shebang line was ignored it should have worked the same way right...

Code:
echo $SHELL
/usr/bin/ksh



Code:
$ ./file.sh
329
Value is  329
Value=329

Thanks anyways.. ill keep this in mind!
# 4  
Old 09-16-2011
Quote:
Originally Posted by justchill
Wow!! it works fine..

But im suprised at the fact that my parent shell is a Korn shell too, so even if the shebang line was ignored it should have worked the same way right...
[...]
No, unless you invoke the script as:

Code:
ksh <script_name>

sh is a KornShell variant by default on limited number of systems (it is on HP-UX for example, on Solaris it's the old Bourne shell, on Linux it's usually a link to bash (on RedHat based systems) or dash (on Debian based systems)).

Consider also that the SHELL variable usually contains your login shell which may or may not be your current shell.

Last edited by radoulov; 09-16-2011 at 07:35 AM..
This User Gave Thanks to radoulov For This Post:
# 5  
Old 09-16-2011
Thanks radoulov for this useful information.
# 6  
Old 09-16-2011
Quote:
Originally Posted by justchill
Can anyone please tell me y the value is not retained.
I respectfully disagree with radoulov. The reason, why your value is not retained is because it is incremented in a subshell. This is not because of the shebang line being ignored or not, but because any command - and "sh" is a command too - is invoking its own process.

You will notice that inside your process the value is retained all right. Consider the following example script:

Code:
#!/bin/ksh

typeset -i iValue=0
typeset   chFile=""

print - "Value before: $iValue"

cat filelist | while read chFile ; do
     (( value += 1 ))
done

print - "Value after: $iValue"

exit 0

But you didn't try to retain the variable throughout a script but you inherited the variable from your commandline environment, modified it in your script and expected it to change it in the orginal commandline environment.

The problem is that when an environment inherits values it does not get the originals but copies of them - with the same names and values but still copies. If you modifiy them you are still modifying the copies, not the originals.

You can overcome this by using the ".", which tells the shell not to start a subshell but execute the script in the environment it already has:

Code:
# sh /some/script.sh
# . sh /some/script.sh

I hope this helps.

bakunin
# 7  
Old 09-16-2011
Quote:
Originally Posted by bakunin
I respectfully disagree with radoulov. The reason, why your value is not retained is because it is incremented in a subshell.
Hi bakunin,
if I'm not missing something, in the OP's example the value of the variable is not incremented in a subshell
(unless executed by the Bourne shell, because it seems that sh uses a subshell for redirected loops):

Code:
while read ...
Value=`expr $Value + $Count`
...
echo "Value=$Value"

Something like:

Code:
$ unset v
$ while read ; do v=$REPLY; done<<<1
$ echo $v
1

The OP is verifying the value of the variable inside the script, not outside of it.

Your cat ... | while read ... example demonstrates another KornShell feature: the last builtin command in a pipeline being executed in the parent shell.

Consider the following examples:

Code:
$ echo ok > infile
$ sh -c 'cat infile | while read v; do myvar=$v;done; echo $myvar'

$ bash -c 'cat infile | while read v; do myvar=$v;done; echo $myvar'

$ ksh -c 'cat infile | while read v; do myvar=$v;done; echo $myvar'
ok

This is because of the previously mentioned KornShell feature.

And this is the OP's case:

Code:
$ echo ok > infile
$ sh -c 'while read v; do myvar=$v;done<infile; echo $myvar'

$ ksh -c 'while read v; do myvar=$v;done<infile; echo $myvar'
ok
$ bash -c 'while read v; do myvar=$v;done<infile; echo $myvar'
ok

In this case the old Bourne shell behaves differently.

Regards
radoulov

P.S. Actually this aspect of some implementations of the Bourne shell is covered in the FAQ.

Last edited by radoulov; 09-16-2011 at 09:33 AM.. Reason: Clarification.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

Variable Scope in Perl

I have to admit that i have not used Perl at all and this is a singular occasion where i have to patch an existing Perl script. I dearly hope i do not have to do it again for the next 15 years and therefore try to avoid having to learn the programming language in earnest. The OS is AIX 7.1, the... (2 Replies)
Discussion started by: bakunin
2 Replies

2. Shell Programming and Scripting

Maintain Scope of the variable in UNIX

Hi All Is there is any way to maintain the scope of the variable in unix Example x=1 j=1 while do .. .... .... while do .. .. x=x+1 done #inner most while loop ends here done #outer loop ends here (8 Replies)
Discussion started by: parthmittal2007
8 Replies

3. Shell Programming and Scripting

Variable scope in bash

Hello! Before you "bash" me with - Not another post of this kind Please read on and you will understand my problem... I am using the below to extract a sum of the diskIO on a Solaris server. #!/bin/sh PATH=/usr/bin:/usr/sbin:/sbin; export PATH TEMP1="/tmp/raw-sar-output.txt$$"... (3 Replies)
Discussion started by: haaru
3 Replies

4. UNIX for Dummies Questions & Answers

Bash loops and variable scope

Hi All, I've been researching this problem and I am pretty sure that the issue is related to the while loop and the piping. There are plenty of other threads about this issue that recommend removing the pipe and using redirection. However, I haven't been able to get it working using the ssh and... (1 Reply)
Discussion started by: 1skydive
1 Replies

5. Shell Programming and Scripting

Variable value not retaining outside function

Hi All, As per my understanding, value of variable is retained outside function. But the value of array myarrayDriver is not retained outside function. Could you please tell the reason for the same.. code: readingConfigFile() { search_keyword="$1" i=0 for pointer in $(cat... (7 Replies)
Discussion started by: ajincoep
7 Replies

6. Shell Programming and Scripting

variable scope

Hi, I want to know about the variable scope in shell script. How can we use the script argument inside the function? fn () { echo $1 ## I want this argument should be the main script argument and not the funtion argument. } also are there any local,global types in shell script? if... (3 Replies)
Discussion started by: shellwell
3 Replies

7. Shell Programming and Scripting

scope of the variable - Naga

Hi All, I am new to unix shell scripting, in the below script "num" is an input file which contains a series of numbers example : 2 3 5 8 I want to add the above all numbers and want the result finally outside the while loop. it prints the value zero instead of the actual expected... (13 Replies)
Discussion started by: nagnatar
13 Replies

8. Shell Programming and Scripting

variable not retaining value

Bourne shell Solaris I'm trying to set a flag to perform an action only when data is found. So I initialize the flag with: X=0 Then I read the data: if ; then while read a b c do X=1 done < ${inputFile} fi The problem is that X will be set to 1 inside the while loop but when... (5 Replies)
Discussion started by: gillbates
5 Replies

9. Programming

C++ variable scope and mutexes

I've been wondering if I can make mutexes much easier to use in C++ with creative use of a locking class and variable scope, but I'm not sure if things happen in the order I want. Here's pseudocode for something that could use the class: int someclass::getvalue() { int retval; ... (0 Replies)
Discussion started by: Corona688
0 Replies

10. Shell Programming and Scripting

Parsing data and retaining the full length of variable

Here's is an example of what I want to do: var1="Horse " var2="Cat " var3="Fish " for animals in "$var1" "$var2" "$var3" do set $animals pet=$1 ## Ok, now I want to get the values of $pet, but ## I want to retain the full length it was... (3 Replies)
Discussion started by: app4dxh
3 Replies
Login or Register to Ask a Question