This question already has an answer here:

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...

marked as duplicate by RalfFriedl, Thomas, mosvy, Jeff Schaller, muru Nov 21 at 1:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 10 down vote accepted

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"

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.