0

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
  • 1
    `$(is_empty)` is, by virtue of `$( )`, in a subshell. A subshell is a whole new copy of the process; when it exists, all its variables and other local state is lost. If you want a function to be able to change variables, call it directly in the interpreter running your script, not in a command substitution or other subshell. – Charles Duffy Feb 11 '22 at 01:22
  • 1
    And as an aside, the only standard compliant string comparison operator in `[` is `=`, not `==`. See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Feb 11 '22 at 01:24

0 Answers0