-2

enter image description here

I want to make a simple calculator but this keeps bugging me up why is this happening anyone ??

# !/bin/bash 
  
# Take user Input 
echo "Enter Two numbers : "
read a 
read b 
  
# Input type of operation 
echo "Enter Choice :"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch 
  



if (($ch==1))
then
  res = $((a + b))
elif (($ch==2))
  then
    res = $((a - b))
elif (($ch==3))
  then
    res = $((a * b))
elif (($ch==4))
  then
    res = $((a / b))
else
  echo ERROR
fi
echo Result is $res

i tried the case statement but same.

braX
  • 11,506
  • 5
  • 20
  • 33
HaDi
  • 7
  • 3
  • 2
    Please take a look at [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Cyrus Apr 01 '23 at 10:39
  • 4
    Replace image with its text. – Cyrus Apr 01 '23 at 10:40
  • 4
    In shell, (unquoted) spaces are delimiters. So, there must be no space around the `=` in an assignment. `var = val` is not interpreted as an assignment but the command `var` with the arguments `=` and `val`. – M. Nejat Aydin Apr 01 '23 at 10:55
  • 2
    Please add a **valid** shebang (`#!/bin/bash`) to your script, then paste it at http://www.shellcheck.net/ and try to implement all the recommendations made there. – Cyrus Apr 01 '23 at 11:07
  • 1
    And consider a `case` statement instead of a series of if-else's to improve your code readability and maintainability. – Ed Morton Apr 01 '23 at 12:13
  • Also see [What is the rationale behind variable assignment without space in bash script](https://stackoverflow.com/q/56910878/4154375). – pjh Apr 01 '23 at 12:40
  • In fact, there technically is no separate assignment *statement* in shell, at least syntactically. Assignments are *words* in (pre)command position that contain at least one `=`. If a line consists only of assignment words and no command, then the assignments take place in the current shell instead of the environment of the command. – chepner Apr 01 '23 at 17:58

1 Answers1

0

In general, it is a good idea to let shellcheck look at your script before you post it. In this case, shellcheck will inform you:

Line 1:
# !/bin/bash
 ^-- SC1115 (error): Remove spaces between # and ! in the shebang.
 
Line 21:
  res = $((a + b))
      ^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).
 
Line 24:
    res = $((a - b))
        ^-- SC2283 (error): Remove spaces around = to assign (or use [ ] to compare, or quote '=' if literal).

et cetera. I left out the informational messages.

And with the corrections suggested by shellcheck, your calculator works fine.

Oh, and please do not post images of text. See XKCD.

Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31