1

I'm trying to do floating point arithmetic in a shell script. I learned that awk can do it on the command line, but the way it works there does not seem to carry over to a shell script. When I type awk below, it turns gray, as if to say that bash doesn't recognize it. When I run it, $ ./script a 30 40, I get 0. What am I doing wrong?

#!/bin/bash
if [ $1 = a ]
then
     echo | awk '{print $2 + $3}'
1
  • 1
    Hint: what does bare echo do in general? So what does echo do in your script? Sep 17 '19 at 21:13
3
#!/bin/bash
if [ $1 = a ]
then
     echo "$@" | awk '{print $2 + $3}'
fi

The $2 and $3 are not related to $1 of the script but are in awk.

3

Consider this if you always trust the args being passed to it:

$ cat script
awk 'BEGIN{ print '"$*"' }'

$ ./script 30 + 40
70

$ ./script 30 \* 40
1200

$ ./script 30 / 40
0.75

Note the need to escape * as it's a globbing char, otherwise quote the args, e.g.:

$ ./script '30 * 40'
1200

Also, with this approach you're not limited to simple arithmetic expressions:

$ ./script 'log(10)'
2.30259

$ ./script 'exp(10)'
22026.5

$ ./script '10^2 - sqrt(9)'
97

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.