Im trying to implement simple stack via functions. Have variable $top which keeps track of the stack showing where the top is. its declared as global and initiated with 0 value. In push() $top var is incremented but call to is_empty() from pop() function is showing that top wasnt mutated. I checked after push() function then called is_empty() from there and still $top was unchanged. what I`m missing? thanks
#!/bin/bash
#set -x
stack_size=4
top=0
make_empty(){
top=0
}
is_empty(){
if [ "$top" -eq 0 ] ###after call from pop() goes here $top has value of 0
then echo 0
else echo 1
fi
}
is_full(){
if [ "$top" -eq "$stack_size" ]
then echo 0
else echo 1
fi
}
push(){
if [ $(is_full) -eq 0 ]
then
echo "Stack overflow"
exit
else
contents[$top]="$1"
((top++)) ###after increment its mutating if checked here
fi
}
pop(){
if [ $(is_empty) -eq 0 ]
then echo "Parenthasys arent matched"
exit
else
((--top))
echo "${contents[$top]}"
fi
}
read -p "Read parentheses: " word
while read -n 1 letter
do
if [ "$letter" == "(" ] || [ "$letter" == "{" ]
then (push "$letter")
elif [ "$letter" == ")" ] && [ "$(pop)" != "(" ]
then echo "not nested properly"
elif [ "$letter" == "}" ] && [ "$(pop)" != "{" ]
then echo "not nested properly"
elif [ "$letter" == " " ]
then
if [ $(is_empty) -eq 0 ]
then echo "matched"
break
fi
else echo "not nested properly"
fi
done < <(echo "$word")
exit