Search code examples
bashdateterminaljobsps

It is possible to sort the proccesses by a given date in bash?


All I'm trying to do is to sort the processes by an input date. This is how I saved the date:

#!/bin/bash
echo "Insert the date yyyy-mm-dd"
read a
if ! [[ $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
then echo "Date is not valid"
elif b=`date --date=$a '+%Y-%m-%d'`
then 
????
fi

How can I show the processes at this date? Thanks.


Solution

  • You can specify a formatter and use lstart, like this command:

    ps -eo lstart,pid,cmd
    

    The above command will output all processes, with formatters to get date+time, PID started, and command run, but i have changed the date format to be align with your date input

    This is what you looking for :

    #!/bin/bash
    declare -A MONTHS
    #months Dictionary
    
    MONTHS[01]=Jan
    MONTHS[02]=Feb
    MONTHS[03]=Mar
    MONTHS[04]=Apr
    MONTHS[05]=May
    MONTHS[06]=Jun
    MONTHS[07]=Jul
    MONTHS[08]=Aug
    MONTHS[09]=Sep
    MONTHS[10]=Oct
    MONTHS[11]=Nov
    MONTHS[12]=Dec
    
    echo "Insert the date yyyy-mm-dd"
    IFS="-" read -a val
    
    if [[ "${val[0]}-${val[1]}-${val[2]}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
    then
        echo "Date is valid!!"
        ps -eo lstart,pid,cmd --sort=start_time | \
        awk {'print $5 "-" $2 "-" $3 " " $6 " " $7'} | \
        grep "${val[0]}-${MONTHS[${val[1]}]}-${val[2]}"
    
    else
        echo "Date is not valid"
    fi
    

    output sample :

    2020-May-19 23 [crypto]
    2020-May-19 230 [scsi_tmf_27]
    2020-May-19 231 [scsi_eh_28]
    2020-May-19 232 [scsi_tmf_28]
    2020-May-19 233 [scsi_eh_29]
    2020-May-19 234 [scsi_tmf_29]
    2020-May-19 235 [scsi_eh_30]
    2020-May-19 236 [scsi_tmf_30]
    2020-May-19 237 [scsi_eh_31]
    2020-May-19 238 [scsi_tmf_31]
    2020-May-19 239 [scsi_eh_32]
    2020-May-19 2390 /usr/lib/deja-dup/deja-dup-monitor