bashfloating-pointprintf

bash printf broken for floats


I have a bash script that gets battery information.

Here's part of it:

#!/bin/bash

if [ -f /sys/class/power_supply/BAT0/energy_full ]; then
  EF=$( echo $(cat /sys/class/power_supply/BAT0/energy_full)/1000000|bc -l ) 
  [ -n "$EF" ] && printf "energy_full: %0.2f Wh\n" $EF
fi

This script worked for a long time then suddenly stopped working.

As an example, the $EF variable will contain 63.71100000000000000000 but the output of printf is a very long number nine lines long that starts with -7309889081043958068.

I tried using just %f but no luck. If I use %d it will print the integer before the decimal point but complain about an invalid number.

I'm using Debian testing.

GNU bash, version 5.2.32(1)-release (x86_64-pc-linux-gnu)

With set -x

+ '[' -f /sys/class/power_supply/BAT0/energy_full ']'
++ bc -l
+++ cat /sys/class/power_supply/BAT0/energy_full
++ echo 63711000/1000000
+ EF=63.71100000000000000000
+ '[' -n 63.71100000000000000000 ']'
+ printf 'energy_full: %0.2f Wh\n' 63.71100000000000000000
energy_full: -nan Wh

Just putting printf 'energy_full: %0.2f Wh\n' 63.711 into a script produces the same error.

I'm using British UK locale. The script used to work.

/bin/printf works, so I can use it as a workaround. Output: energy_full: 63.71 Wh


Solution

  • This is a known bug. A patch is available here: mail.gnu.org/archive/html/bug-bash/2024-08/msg00027.html

    ā€” comment by oguz ismail