UNIX脚本计算器中MR指令无法重新赋值operand2变量的问题
Shell计算器MR指令失效问题修复
这段Shell脚本是计算器的内存操作模块,支持MS(存内存)、MR(读内存)、M+(内存累加)指令,但输入"MR"时,operand2始终保持字符串"MR",无法读取mem中存储的值。
原代码:
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
问题根源
代码中MS和MR分支的赋值语句用了括号(),这会创建子shell执行赋值操作。子shell是独立的进程,它内部的变量修改不会同步到父shell。比如MR分支里,你在子shell里把operand2设为mem的值,但子shell退出后,父shell的operand2还是最初读取的"MR"。
修复方案
去掉赋值语句外的括号,直接在当前shell环境下修改变量:
修改后的代码:
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
这样修改后,MS分支会把sum的值存入当前shell的mem变量,MR分支也能正确把mem的值赋给operand2,退出循环后后续逻辑就能使用这个值了。
内容的提问来源于stack exchange,提问作者Snowbird2001
相关产品推荐
相关产品推荐

