Ankur Agarwal
Ankur Agarwal

Reputation: 24748

Setting variable in while loop condition

GNU bash, version 4.1.5(1)-release-(i486-pc-linux-gnu) Ubuntu Linux 10.04

This prints var as 1234 and does not print var2

#!/bin/bash

var=1234

while var=9876 var2=765 read line
do

    echo $var $var2
    echo $line

done <datafile

echo out of loop $var

o/p

1234
This is line 1
1234
This is line 2
1234
This is line 3
1234
This is line 4
1234
This is line 5
1234
This is line 6
1234

out of loop 1234

This prints var as 9876 and also prints var2

#!/bin/bash

var=1234

while 
var=9876 
var2=765 
read line
do

    echo $var $var2
    echo $line

done <datafile

echo out of loop $var

o/p

9876 765
This is line 1
9876 765
This is line 2
9876 765
This is line 3
9876 765
This is line 4
9876 765
This is line 5
9876 765
This is line 6
9876 765

out of loop 9876

Why is that?

Upvotes: 0

Views: 568

Answers (1)

shellter
shellter

Reputation: 37248

Edit I see now that your first script IS producing output of 1234. This is happening because var1 is scoped in the main script BUT the read is silently consuming var1 and var2 because they are scoped locally to just the line var=9876 var2=764 read ... as I describe below.

mostly orig post : Per old school unix, a command-line can contain pre-pended variable assignments whose scope is only the command immediately following.

So your line

while var=9876 var2=765 read line
      ^--prepened Vars--^cmd^args

is parsed like the ^--- indicate.

Because the pre-pended vars belong only to the command they are 'attached' to, in this case read, they are only visible to that process. (read is probably an internal command, this may be part of the problem).

By contrast, your second block of code,

while 
var=9876 
var2=765 
read line

each var assignment is executed inside the current shell, and they do not 'belong' to the read command becuase they are not exported.

Thanks for the OS and bash version, but this is 'functioning as designed' for bash, ksh, zsh, and probably others. If you just want to know why this is happening for intellectual curiosity, then you'll need to spend time reading advanced bash scripting. If this represents a real problem for your code, then you'll have to post a new question with more details about what you are trying to accomplish.

I hope this helps.

Upvotes: 2

Related Questions