2

Utilizing bash to multiply an interger by a float with an if statement, I will further expand on this with two other cases outside 0.90, just trying to learn the basics.

#!/bin/bash echo -n "give me an integer: [ENTER]: " read that_integer if -n [ $that_integer <= 5000 ]; then awk print $that_integer*0.90 done 

Ultimately, this is the code I came up with.

Thanks!

#!/bin/bash echo "give me an integer: [ENTER]: " read that_integer if [ $that_integer -le 5000 ]; then awk -v x=$that_integer 'BEGIN { print x*0.90 }' < /dev/null elif [ $that_integer -gt 5000 -a $that_integer -le 50000 ]; then awk -v x=$that_integer 'BEGIN { print x*0.70 }' < /dev/null else awk -v x=$that_integer 'BEGIN { print x*0.40 }' < /dev/null fi done 
1
  • +1 for good early question. Of course you could do all of this in 1 line of awk, (with only 1 process creation in all cases), i.e. awk -v i=$that_int 'BEGIN{if (i<5000) print i*.9 else if (i>5000 && i <=50000) print i*.7 else print i*.4}' Good luck and keep poinsting. Commented Sep 23, 2014 at 22:30

3 Answers 3

1

You can use the bc utility to do floating point arithmetic in the shell.

echo "give me an integer: [ENTER]: " read that_integer if [ $that_integer -le 5000 ]; then echo "$that_integer*0.90"|bc elif [ $that_integer -gt 5000 -a $that_integer -le 50000 ]; then echo "$that_integer*0.70"|bc else echo "$that_integer*0.40"|bc fi 
Sign up to request clarification or add additional context in comments.

Comments

0

The -n does nothing; remove it.

For integer comparisons, use -le:

if [ $that_integer -le 5000 ]; then 

The correct syntax for the awk call is

awk -v x=$that_integer 'BEGIN { print x*0.90 }' < /dev/null 

if statements are terminated with fi, not done.

3 Comments

You don't need < /dev/null in awk
Right but with BEGIN it won't need it. awk -v x=4 'BEGIN{print 5*x}' also works.
Ah, didn't realize that if the only rule is a BEGIN rule, it would ignore standard input.
0

As you know, bash can't handle floats, but you can re-cast this to use integer maths:

x=$((5000*90/100)) echo $x 4500 

So, just for kicks:

#!/bin/bash echo "give me an integer: [ENTER]: " read that_integer multiplier=40 [ $that_integer -le 5000 ] && multiplier=90 [ $that_integer -gt 5000 -a $that_integer -le 50000 ] && multiplier=70 echo $(($that_integer*$multiplier/100)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.