A Balderrama
A Balderrama

Reputation: 3

Call a function inside an if statement bash

I have these code in bash, but i need to call the functions inside the if statement but it doesn't work any ideas?

v="1"
if [ "$v" != "1" ]; then
        yes
else
        no
fi


yes(){
        echo "the value is "$v""
}
no(){
        echo ""$v" same value"
}

Upvotes: 0

Views: 2979

Answers (1)

chepner
chepner

Reputation: 531185

Your if statement is fine; you simply need to define the functions before you attempt to call them.

yes(){
        echo "the value is $v"
}
no(){
        echo "$v same value"
}

v="1"
if [ "$v" != "1" ]; then
        yes
else
        no
fi

(bash, being dynamically scoped, will use whatever variable v is in scope at the time it is called.)

Upvotes: 2

Related Questions