wantlolearn
wantlolearn

Reputation: 17

shell script that displays the processes launched in the background

I have a little problem here. I am trying to write a script shell that shows background processes, but at a certain date. The date is a positional parameter. I've searched on Internet about the date validation, but all the info I found got me confused. I'm fairly new at this so a little help would be appreciated.

How do I verify if the date parameter is in a valid format in my shell script?

Upvotes: 1

Views: 87

Answers (2)

Mahmoud Odeh
Mahmoud Odeh

Reputation: 950

you can use regex :

#! /bin/bash

isDateInvalid()
{
    DATE="${1}"

    # Autorized separator char ['space', '/', '.', '_', '-']
    SEPAR="([ \/._-])?"

    # Date format day[01..31], month[01,03,05,07,08,10,12], year[1900..2099]
    DATE_1="((([123][0]|[012][1-9])|3[1])${SEPAR}(0[13578]|1[02])${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[01..30], month[04,06,09,11], year[1900..2099]
    DATE_2="(([123][0]|[012][1-9])${SEPAR}(0[469]|11)${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[01..28], month[02], year[1900..2099]
    DATE_3="(([12][0]|[01][1-9]|2[1-8])${SEPAR}02${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[29], month[02], year[1904..2096]
    DATE_4="(29${SEPAR}02${SEPAR}(19|20(0[48]|[2468][048]|[13579][26])))"

    # Match the date in the Regex

    if ! [[ "${DATE}" =~ "^(${DATE_1}|${DATE_2}|${DATE_3}|${DATE_4})$" ]]
    then
        echo -e "ERROR - '${DATE}' invalid!"
    else
        echo "${DATE} is valid"
    fi
}

echo
echo "Exp 1: "`isDateInvalid '12/13/3550'`
echo "Exp 2: "`isDateInvalid '12/11/20322'`
echo "Exp 3: "`isDateInvalid '12 01 2000'`
echo "Exp 4: "`isDateInvalid '28-02-2014'`
echo "Exp 5: "`isDateInvalid '12_02_2002'` 
echo "Exp 6: "`isDateInvalid '12.10.2099'`
echo "Exp 7: "`isDateInvalid '31/11/2020'`

Upvotes: 1

Nstevens
Nstevens

Reputation: 327

If I'm understanding correctly, you want to input a date and filter background processes by that input and you are looking for a way to validate the input using the shell?

If you can break out the year/month/day into a slash-separated format, you can use the date command to test if the date stamp is valid. This runs under bash, other shells may be different

bad

$ echo -n "year :"; read year; echo -n "month :"; read month; echo -n "day :"; read day; date -d "$year/$month/$day" || echo "Not a valid date"
year :9999
month :32
day :32
date: invalid date ‘9999/32/32’
Not a valid date

good

$ echo -n "year :"; read year; echo -n "month :"; read month; echo -n "day :"; read day; date -d "$year/$month/$day" || echo "Not a valid date"
year :2020
month :3
day :23
Mon Mar 23 00:00:00 CDT 2020

Upvotes: 1

Related Questions