shelldatesunos

How to check the date format as YYYYMMDD using Solaris shell command?


I have searched all over but the option to display the date format in SunOS 5.10 is present, but no answers for how to check the valid format as per our requirements.

#!/bin/bash
date +'%Y%m%d' -d "$4" 2>&1 >> ${LOG_FILE}
is_valid=$?
if [ $is_valid -eq 1 ];then
   echo "Invalid date format"
   exit 2
fi

When I execute the command I pass the date in the option and if the date format is not correct the shell should exit. This format check command is not working in SunOS.


Solution

  • I don't think the SunOS 5.10 version of date accepts the -d option. However, it does provide the cal command. As your date format is all digits, it is quite easy to split into year, month and day, feed the month and year into cal and then use grep to look for the day. Something like:

    #!/usr/xpg4/bin/sh
    
    case "$1" in
        [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])
            Y=${1%????}
            t=${1#????}
            m=${t%??}; m=${m##0}
            d=${t#??}; d=${d##0}
            if [ -n "$(cal "$m" "$Y" 2>&1 | grep "\<$d\>")" ]; then
                echo ok
            else
                echo no
            fi
            ;;
        *)
            echo no
            ;;
    esac
    

    Note: Untested, as I no longer have any Solaris 10 machines.