0

I need to detect whether the current minutes are even or odd regardless of the time zone ! I tried this according to answers from several sites:

#!/bin/bash 
n=$(date +"%M")
r=`expr$n%2`
if [ r -eq 0 ] 
then 
echo "Even minute"
else 
echo "Odd minute"
 fi
New contributor
freetoair is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
4
  • What is the question?
    – Toto
    Commented yesterday
  • What is wrong here, because when I run the script I get :
    – freetoair
    Commented yesterday
  • ./Odd_even.sh: line 5: expr04%2: command not found ./Odd_even.sh: line 6: [: r: integer expression expected
    – freetoair
    Commented yesterday
  • expr is an external command like ls and like any command you are required to use spaces to separate the command from its arguments. Commented yesterday

1 Answer 1

2

Working with hours or minutes as numbers in bash has a nasty edge case: bash treats numbers with a leading zero as octal, and 08 and 09 are invalid octal numbers:

min=09
echo $(( min % 2 == 0 ))
bash: 09: value too great for base (error token is "09")

Use %-M as the format directive -- it will return the minutes with no leading zero.


Additionally:

  1. bash can do arithmetic, you don't need to call out to expr

    if (( n % 2 == 0 )); then
      echo "$n is even"
    else
      echo "$n is odd"
    fi
    
  2. and bash can do strftime-like things. The %()T directive in bash's builtin printf allows the date format string inside the parentheses. In this simple case, you don't need to call out to date.

    minute=$(printf '%(%-M)T' -1)   # -1 is a special value that means "now"
    # or even
    printf -v minute '%(%-M)T' -1
    
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .