3

I want to set a variable if my condition is true on my Ubuntu system.

This proves that my if-statement is correct:

$ (if [ 1 == 1 ]; then echo "hi there"; fi);
hi there

This proves that I can set variables:

$ a=1
$ echo $a
1

This shows that setting a variable in the if-statement DOES NOT work:

$ (if [ 1 == 1 ]; then a=2; fi);
$ echo $a
1

Any ideas why? All my google research indicates that it should work like this...

0

3 Answers 3

10

The (...) part of your command is your problem. The parentheses create a separate subshell. The subshell will inherit the environment from its parent shell, but variables set inside it will not retain their new values once the subshell exits. This also goes for any other changes to the environment inside the subshell, including changing directories, setting shell options etc.

Therefore, remove the subshell:

if [ 1 = 1 ]; then a=2; fi
echo "$a"
5

This proves that setting a variable in a sub-shell has no lasting effect

(if [ 1 == 1 ]; then a=2; fi);
echo $a

produces

1

same as

(a=2)
echo $a

produces

1

Solution remove the parenthesis.

if [ 1 == 1 ]; then a=2; fi;
echo $a

produces

2

or if you need a sub-shell

(
  if [ 1 == 1 ]; then a=2; fi;
  echo $a
)

produces

2
-2

It done by below method and it worked fine

_example ~]# if [[ 1 == 1 ]]; then echo "praveen"; a=2; echo $a; fi| sed '1i================================\n output'
================================
 output

praveen
2
2

Not the answer you're looking for? Browse other questions tagged .