0

Hello I am trying to make a simple bash script and am very new to it.

With the the if statement I am trying to count up like a clock.

So the output would be for example 16:59:58, 16:59:59, 17:00:00

The seconds and minutes work, however the first if statement is not working.

When it gets to 23:59:59, it is meant to go to 00:00:00 however it goes to 24:60:00

Any help?

if [[ "$hours" -eq 23 && "$minutes" -eq 60 && "$seconds" -eq 60 ]]
then
    seconds=0
    minutes=0
    hours=0
    ((date++))
else
    if [[ "$minutes" -eq 60 ]]
    then
        minutes=00
        ((hours++))
    else
        if [[ "$seconds" -eq 60 ]]
        then
            seconds=00
            ((minutes++))
        fi
    fi
fi
7
  • What's date? How are you actually incrementing seconds? Commented Feb 10, 2020 at 16:47
  • There's also an elif clause available, so that you don't have to nest if statements like this. Commented Feb 10, 2020 at 16:48
  • Cool trick, you can write scripts inside (( and if's with ? : ternary operator. (( hours == 23 && minutes == 60 && seconds == 60 && ( seconds = 0, minutes = 0, hours = 0, date++ ) )). to 23:59:59 - then you should compare with 59 not with 60. Commented Feb 10, 2020 at 16:49
  • 1
    "$hours" -eq 23 should be "$hours" -eq 24. You're testing the value after it has been incremented. Commented Feb 10, 2020 at 16:49
  • The way you've written it, it will go from 22:59:59 to 0:0:0. Commented Feb 10, 2020 at 16:51

1 Answer 1

1

Work from the lowest order field up, instead of testing all the variables.

((seconds++))
if [[ $seconds -eq 60 ]]
then 
    seconds=0
    ((minutes++))
fi
if [[ $minutes -eq 60 ]]
then
    minutes=0
    ((hours++))
fi
if [[ $hours -eq 24 ]]
then
    hours=0
    ((date++))
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.