0

I need to do the follwing with bash what is the elegant way ? to get the final $sum value

worker_machine=32
executors_per_node=3

executer=$worker_machine/$executors_per_node-1
spare=$executer X 0.07 
sum=$executer-$spare ( with round the number to down ) 

example:

32/3 = 10 - 1 = 9
9 X 0.7 = 0.6
9 – 0.6 = 8 ( with round the number to down ) 
  • 1
    The shell will not do floating point arithmetics for you, so that rules out e.g. $(( ... )). The best option would be to use awk IMHO. – Kusalananda Feb 11 '18 at 17:39
  • can you so me the complete answer please – jango Feb 11 '18 at 17:50
  • Patience is a virtue ;-) – Kusalananda Feb 11 '18 at 17:53
  • Is the first example (32/3)-1 = 10 - 1 = 9? This is, what $((32/3-1)) will perform. – user unknown Feb 14 '18 at 20:15
1

Using awk, taking values from shell variables:

awk -v n="$worker_machine" -v m="$executors_per_node" \
    'BEGIN { printf("%d\n", 0.93 * (n / m - 1)) }' /dev/null

The awk script doesn't get any input as usual, so we use /dev/null as input file and do our calculation and output in a BEGIN block.

Using bc:

sum=$( printf '0.93 * (%d / %d - 1)\n' "$worker_machine" "$executors_per_node" | bc )
printf '%.0f\n' "$sum"

Using dc:

sum=$( printf '%d\n%d\n/\n1\n-\n0.93\n*\np\n' "$worker_machine" "$executors_per_node" | dc )
printf '%.0f\n' "$sum"
  • 1
    @Inian But when it's done with the BEGIN block, it would wait for input from the terminal if not provided a file. – Kusalananda Feb 11 '18 at 18:02
  • 1
    @Inian Hrm... no it doesn't. My bad. But I'll leave it in there because it serves to document the fact that we're not reading from anywhere. – Kusalananda Feb 11 '18 at 18:04
0

The shell is able to to the math (as integers, which round down):

$ sum=$(( ( worker_machine/executors_per_node-1 ) * 93 / 100 ))
$ echo "$sum"
8

The default scale for bc is 0, so the results of division would be integers:

$ sum=$(bc <<<"($worker_machine / $executors_per_node - 1)*93/100")
$ echo "$sum"
8

As we want an integer, we may ask awk for one

$ sum=$(awk -v m="$worker_machine" -v n="$executors_per_node" 'BEGIN{ print( int((m/n-1)*93/100) )}' /dev/null)
$ echo "$sum"
8

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.