Setting a variable within if block

Hi,

i have a variable which i would like to set inside an if block

for example

IS_VAR=0
if [ "true" = "true" ]
then
 IS_VAR=1
fi
echo IS_VAR  

the last echo statement gives 0.So setting variables in the if block doesnt have effect outside the block?Is there any workaround for this?

Thanks ,
Padmini

nothing like that.. $ is missing from your last echo statement

home/vidya_perl> cat vv
IS_VAR=0
if [ "true" = "true" ]
then
IS_VAR=1
fi
echo $IS_VAR
home/vidya_perl> vv
1

Hi,

i use echo $IS_VAR only.

and the example is slightly modified here

its like,
I

S_VAR=0
ls | while read input
do
if [ $input = "hi" ]
then
  IS_VAR=1
  echo $IS_VAR
  break
fi
done
echo $IS_VAR

for the first echo , i get 1 and for the second i get 0.

Yes,looks the initialization inside the while block has no effect outside the while block.
But if you remove while then output 1 and 1.

#!/bin/sh

IS_VAR=5
input="hi"

if [ $input = "hi" ];then    
    IS_VAR=1
    echo $IS_VAR
fi

echo $IS_VAR

The pipe starts a new shell (child) so the assigned value of the variable is lost after the loop.

Try something like this:

IS_VAR=0

list=$(ls)

for input in $list
do
if [ $input = "hi" ]
then
  IS_VAR=1
  echo $IS_VAR
  break
fi
done
echo $IS_VAR

Regards

The script does work for me...

> cat Test
#!/bin/sh

touch hi
echo Outside $PPID $$
ls | while read input
do
if [ $input = "hi" ]
then
  echo Inside $PPID $$
  IS_VAR=1
  echo Inside $IS_VAR
  break
fi
done
  echo Output $PPID $$
echo Outside $IS_VAR
> ./Test
Outside 13426702 2252968
Inside 13426702 2252968
Inside 1
Output 13426702 2252968
Outside 1

Which OS are you using, Padmini?

Edit: Wow... It works on AIX but not on Linux or Solaris. I do apologise.

It doesn't work in ubuntu.
This is the output:

Outside 9559 9803
Inside 9559 9803
Inside 1
Output 9559 9803
Outside

Are you using AIX?

Yes, I just figured that out. And surprised!

This works only in ksh and its derivates like ksh93 and in zsh.

Regards

Hi,

Its SUSE linux .

---------- Post updated at 10:05 PM ---------- Previous update was at 09:50 PM ----------

Hi,

if i use for loop , the input variable dosnt have the line by line value but the entire output of ls.Can someone tell me how to read it line by line using for loop

The previous example wasn't the best solution, this should be better:

#!/bin/sh

IS_VAR=0

for file in *
do
if [ "$input" = "hi" ]
then
  IS_VAR=1
  echo $IS_VAR
  break
fi
done
echo $IS_VAR

Regards

Hi,

Can someone help me in using awk or sed for finding out if the output contains a particular string.Because i cannot use * here in the for loop.

for example ,
if my output is
string1
string2
string3
string

i want to check if the output has the word "string".if i use grep "string" it shows me all the words displayed in the output.but i just need the output string.i tried using grep "^string$".But this also doesnt help me.

Thanks ,
Padmini