0

I have the below script which is trying to get the pass percentage through shell script.

Script:

  n= "$pass"/"$total";
  "$n" * = 100;
  echo "$n"

Output:

/tmp/jenkins3601870177535319162.sh: line 45: 20/25*=: No such file or directory 20/25

I'm not sure the above calculation is correct. But I just have variable $pass which is having pass test case count and $total variable which had total test case count. Just wanna get percentage of the passed test cases using shell.

ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84

1 Answers1

1

You have two primary problems: (1) there cannot be any spaces on either side of the '=' sign; and (2) shell uses integer math so 20/25 will equal 0.

The POSIX arithmetic operator is ((...)) where your expression goes within ((...)). Also, within ((...)) there is no need to derefernce the variable name by preceding it with a '$'.

To assign the result of the expression to a variable you precede the operator by the '$', e.g. n=$((pass/total)).

To get around the fact that shell uses integer math, you can multiply pass by 100 before you divide and at least get a whole-number percentage. For example:

#!/bin/sh

pass=20
total=25

n=$(((pass * 100)/total))

printf "pass percentage: %d\n" "$n"

If you run the script you will then get:

$ sh percent.sh
pass percentage: 80

Where 80% is what would be the percent result for 20/25. Look things over and let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85