-1

This is essentially part a calculator in UNIX script. In this part of the script, using MR, MS, or M+ will yield different results. Here is the code in question:

while true
do
    echo 'please enter operand'
    read operand2
    if [ "$operand2" = "X" ]
    then
        exit
    fi
    case "$operand2" in
    "MS")
            (mem=$sum)
            echo "$sum -> M"
            continue;;
    'MR')
            (operand2=$mem)
            echo $operand2
            echo "M -> $mem"
            break;;
    'M+')
            temp=$(( sum+mem ))
            echo "$sum + $mem = $temp"
            mem=$(( sum+mem ))
            continue;;
    *[0-9]*)
            break;;
    *)
            echo "Sorry, $operand2 is not a valid input"
            continue;;
    esac
done

The problem with the code is that with the input of "MR", the variable operand2 remains assigned to the string "MR" rather than being reassigned to the value stored in the mem variable.

I have tried adding an echo statement for operand2, as I thought this may be a scope issue, however, the echo returns "MR" anyways. I have also tried moving around the reassignment within the case, which doesn't seem to resolve the issue.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Why did you put parentheses around the assignment? – Shawn Feb 11 '23 at 20:47
  • 3
    Do you know what they do? – Shawn Feb 11 '23 at 20:48
  • 1
    Possible duplicate: [How to use double or single brackets, parentheses, curly braces](/q/2188199/4518341) (though it's much more general) – wjandrea Feb 11 '23 at 20:51
  • 1
    In the future, please make a [mre], which can help you understand the problem better. Here, `case` is irrelevant. You could reproduce the problem in two lines: `(foo=bar); echo $foo` (which prints a blank line) or `(foo=bar); declare -p foo` (which results in an error). – wjandrea Feb 11 '23 at 20:53
  • 1
    Please add a suitable shebang (`#!/bin/bash`) and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus Feb 11 '23 at 21:06

1 Answers1

2

The parentheses around the assignments makes the assignments happen in subshells and the value you set in those subshells will not be visible to the outer shell. Make it

mem=$sum

and

operand2=$mem
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108