简体   繁体   中英

linux shell script printf number format color

Ahead, Sorry for my english sentence. ( I am weak at English )

Here is a source.
I wanna color the ${test} in %d %f format.
But I get an error. Invalid number.

I wanna maintain %d %f format ( for comma and point ) and also want the color.
Please, know the way.

source

#!/bin/sh
warning_color=$(tput setaf 4) # blue
end_color=$(tput sgr0)

test="30000"
result="30000"
if [[ ${test} -gt 20000 ]]
then
  test="${warning_color}${test}${end_color}"
fi
printf "%'10d%'10d\n" "${test}" "${result}"

test="30000.13"
result="30000.13"
if [[ ${test%%.*} -gt 20000 ]]
then
  test="${warning_color}${test}${end_color}"
fi
printf "%'10.2f%'10.2f\n" "${test}" "${result}"

error ( 30000 and 30000.13 color is blue in error message )

a.sh: line 7: printf: 30000: invalid number
     0a.sh: line 11: printf: 30000.13: invalid number
  0.00

You need to add the colours to the format strings, otherwise the numbers are no longer as into or float when you add the color codes to The variables

Ex.

$ blue=$(tput setaf 4)
$ end=$(tput sgr0)
$ val1=3000
$ val2=3000.11
$ printf "$blue %10d $end\n" $val1
        3000
$ printf "$blue %10.2f $end\n" $val2
     3000.11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM