Skip to content
Advertisement

Extra percent sign appears in echo bash

I’ve got the following script below which is supposed to demo CPU utilization:

#!/bin/bash

#Color declarations
RED='33[0;31m'
GREEN='33[0;32m'
BLUE='33[0;34m'
LIGHTBLUE='33[1;34m'
LIGHTGREEN='33[1;32m'
NC='33[0m' # No Color

a=1
b=3
end=$((SECONDS+120))

echo "CPU Utilization:"
echo "1%"

while [ $SECONDS -lt $end ] ; do

        echo -e "${GREEN}e[1A$((a+RANDOM%(b-a))).$((RANDOM%99))%${NC}"

        sleep 1

done

For some reason, when the percentage is echoed out, two percent signs appear instead of the last digit of the number and a percent sign. For example, the output is sometimes 2.7%% instead of 2.72%. Everything works fine when I take the percent sign away, but even if I include a space between the percent sign and the random number generation, the percent sign still appears occasionally. Does anyone know how to fix this issue? Specifically, the issue is with the percent sign here:

echo -e "${GREEN}e[1A$((a+RANDOM%(b-a))).$((RANDOM%99))%${NC}"
                                                        ^

Advertisement

Answer

Your code is overwriting what was already there, but a percentage sign may be left over that doesn’t get overwritten. If the previous result was

2.33%

and this time you’re writing

2.7%

in the same space, it only overwrites the first four characters, so the previous percent character remains. So you should add a space, but after the percent character.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement