0

When i'm trying to execute following line of code

#!/bin/sh
a=20
b=10
sum=`expr $a + $b` #(i thought i did wrong with ` so i put (') also to check but its becomes literals which gets printed as usual)
echo $sum

i'm getting the error

expr: non-integer argument

Can someone tell me where it went wrong in this code because almost on every tutorial same thing was mentioned to do Arithmetic in Shell Script.

Edit: for those whose working i'm using CYGWIN terminal FYI. IS there any difference ?

Edit 2 : As mentioned in the comment by @ghoti Windows file ends with /r/n while unix ends with /n .. Since i'm writing my Script in windows platform while executing in Unix Platform , So when i'm removing back-tick its giving me error

$'20\r': command not found

so definitely $a is changed into 20 but \r is resulting into error. So any ideas how to Short out this error ?

Ankur Anand
  • 3,873
  • 2
  • 23
  • 44
  • are you arguments really number? Also dont use backticks its discouraged. – SMA Mar 10 '15 at 14:06
  • 1
    Works for me in bash and dash, outputs `30`. – choroba Mar 10 '15 at 14:07
  • 4
    Does your script have CRLF line endings? Then you would have `expr 20\r + 10\r` – glenn jackman Mar 10 '15 at 14:10
  • SMA no argument is not really number as Shell store things in String but isn't it where expr comes handy to do Arithmetic Evaluation – Ankur Anand Mar 10 '15 at 14:12
  • Not reproducible [here](http://ideone.com/DuE3BZ). Is this your real script? – n. m. could be an AI Mar 10 '15 at 14:12
  • glenn jackman i think yes because when i removed backticks it was giving me error with such "20/r" : command not found so i guess yes – Ankur Anand Mar 10 '15 at 14:14
  • @n.m. yeah and i'm using CYGWIN Terminal BTW. IS there any difference ? – Ankur Anand Mar 10 '15 at 14:21
  • 2
    @AnkurAnand, in Windows, text files have lines that end with `\r\n`, whereas in unix they end in `\n`. So yes, there is a difference. Do you know how to proceed? – ghoti Mar 10 '15 at 14:26
  • Also, `#!/bin/sh` means that you're running a Bourne or posix shell. If you're using bash, then you're running it in compatibility mode. You should use `#!/bin/bash` if you really want to write bash scripts. – ghoti Mar 10 '15 at 14:27
  • and if you're reallly writing `bash` scripts, then you can use "modern" math processing provided in bash and ksh like `sum=$(( a + b ))`. Good luck to all. – shellter Mar 10 '15 at 15:03
  • @ghoti No i don't any any idea how to proceed .. can you help ? – Ankur Anand Mar 10 '15 at 15:06

2 Answers2

1

I had similar error. I did the following and issue resolved:

Go to Edit in notepad++, then selected EOL Conversion, then selected UNIX/OSX Format

Ravi
  • 239
  • 2
  • 14
0

Your original code should work correctly. Even though, to make sure you don't have any issue with quotes, you can slightly modify it like that:

#!/bin/sh
a=20
b=10
sum=$(expr $a + $b)
echo $sum
MarcM
  • 2,173
  • 22
  • 32