Home > Net >  Special symbols as patterns in bash case statement
Special symbols as patterns in bash case statement

Time:08-09

I'm making simple calculator. User inputs simple expression e.g. 1 2 or 11*4 or 24/2. I need to use case structure to echo calculation like “3 multiplied by 4 equals 12”. Atm case structure does not echo when running the program?

#!/bin/bash

read -p "Give expression example: 42 6 " calc
read NUM1 NUM2 <<<${calc//[^0-9]/ }

case $calc in
    \ )
    echo "$NUM1 plus $NUM2 equals $NUM1 $NUM2"
    ;;
    \-)
    echo "$NUM1 minus $NUM2 equals $NUM1-$NUM2"
    ;;
    \*)
    echo "$NUM1 multiplied by $NUM2 equals $NUM1*$NUM2"
    ;;
    \/)
    echo "$NUM1 divided by $NUM2 equals $NUM1/$NUM2"
    ;;
esac

CodePudding user response:

your $calc is the raw string of the input

#!/bin/bash

read -p "Give expression example: 42 6 " calc
read NUM1 NUM2 <<<${calc//[^0-9]/ }
read oper <<<${calc//[0-9]/}

case $oper in
    \ )
    echo "$NUM1 plus $NUM2 equals $NUM1 $NUM2"
    ;;
    \-)
    echo "$NUM1 minus $NUM2 equals $NUM1-$NUM2"
    ;;
    \*)
    echo "$NUM1 multiplied by $NUM2 equals $NUM1*$NUM2"
    ;;
    \/)
    echo "$NUM1 divided by $NUM2 equals $NUM1/$NUM2"
    ;;
esac
  • Related