Odd and even date in bash

Hi All,

I'm having the following script:

#!/bin/bash

date=$(date +%d)

echo $date

if [ ${date%2} -eq 0 ];

then

echo 'date is even'

else

echo 'date is odd'

fi

but I can not find out why it's not working.Example:

cat test_even.sh 
#!/bin/bash

date=$(date +%d)

echo $date

if [ ${date%2} -eq 0 ];

then

echo 'date is even'

else

echo 'date is odd'

fi
~ $ . test_even.sh 
08
date is odd

 $ date
Fri Nov  8 15:08:18 EET 2013

Please advise,thanks

You should use bash's integer arithmetics. And, btw, using a variable with the same name as a command works, but can become veeery misleading sometime! Try

echo $((10#${date}%2))

You can avoid the base 10 indicator if you use date +%e when assigning the variable.

1 Like

Hi RudiC,

10x for the information but that still don't work even with:

echo $((10#${date}%2))
 cat test_even.sh 
#!/bin/bash

dates=$(date +%d)

echo $((10#${dates}%2))

if [ ${dates%2} -eq 0 ];

then

echo 'date is even'

else

echo 'date is odd'

fi

. test_even.sh 
0
date is odd

OK. echo $((10#${dates}%2)) obviously yields 0, if [ ${dates%2} -eq 0 ]; doesn't. What conclusion would YOU draw?

1 Like

OK. echo $((10#${dates}%2)) obviously yields 0, if [ ${dates%2} -eq 0 ]; doesn't. What conclusion would YOU draw?

Obviously something in

[ ${dates%2} -eq 0 ];

is not correct or I'm missing something?

---------- Post updated at 04:56 PM ---------- Previous update was at 04:50 PM ----------

OK I got it now:

#!/bin/bash

dates=$(date +%d)

echo $((10#${dates}%2))

if [ $((10#${dates}%2)) -eq 0 ];

then

echo 'date is even'

else

echo 'date is odd'

fi


Now it's ok my bad and thanks again for the help:

~ $ . test_even.sh 
0
date is even