Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Why variable $c in end of code not echo "smile" but only echo empty value?

I wont get variable $c after end of "if operator" but when operator finish job my value $c not return "smile" but only return "" (empty value)

#!/bin/bash
###
## sh example.sh

a="aaa"
b="bbb"

if [ "$a" != "$b" ]; then ( 
c="smile"
echo "echo inside if:"
echo $c # in this echo "smile" 
) else ( 
c="yes" 
) fi

echo "echo after fi:"
echo $c  # echo ""  # why this not echo "smile"

result:

[root@my-fttb ~]# sh /folder/example.sh
echo inside if:
smile
echo after fi:

[root@my-fttb ~]#
share|improve this question

2 Answers 2

up vote 6 down vote accepted

Get rid of the parentheses. Parentheses create sub-shells, and variables set in a sub-shell aren't propagated back to the parent shell.

if [ "$a" != "$b" ]; then
    c="smile"
    echo "echo inside if:"
    echo $c  # in this echo "smile" 
else
    c="yes" 
fi
share|improve this answer

The parenthesis if the if statement, creates a sub-shell, so the variables are not changed in the parent shell.

Remove the parenthesis:

if [ "$a" != "$b" ]; then
    c="smile";
    echo "echo inside if:"
    echo $c; # in this echo "smile" 
else
c="yes"; 
fi
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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