0

I have got the commands to pick up the date from a line comparing them with current date, I am looking to print another field from same line in if-then statement.

cat /tmp/OutPrint |cut -d' ' -f 2 | while IFS= read line; do
    
    now=$(date | cut -d' ' -f 4)
    
    time_now=$(date -u -d "$now" +"%s")   #seconds
    time_line=$(date -u -d "$line" +"%s") #seconds
    
    difference=$(echo $((time_now - time_line)))
    
    if [ $difference -ge 2592000 ] 
    then
        echo "Time difference is greater than 30 days"
    else 
        echo "Time difference is less than 30 days"
    fi
done

Below is the content of my file from which I am comparing the date with the current date. If the difference is more than 30 days I need the first field to be printed in the then statement.

How can I print the first field in the then statement ?

Input:

anhtdg5 03-Jul-2019  
kjushr7 04-Aug-2020  
bhyusj3 09-Mar-2017  
losyej9 09-Mar-2017  
nhtgsy57 09-Mar-2017  
bpolise3 09-Mar-2017  
uioshye2 14-Mar-2018   
zsethfyu 23-Nov-2018  
cnhysge 23-Mar-2018  
0

1 Answer 1

1

You want to use the first field, but cut it off before sending it to while.

Why not simply use read to separate the fields:

while read name date; do
    ...
    time_line=$(date -u -d "$date" +"%s")
    ...
    echo "$name"
done < /tmp/OutPrint

Your script has several additional complicated notations that somehow work, but could be written in better ways:

  • Useless use of cat.

  • Why you save an intermediate $now variable to use with date instead of use date directly:

    time_now=$(date -u +"%s")
    
  • Useless use of echo to save an output of command to a variable:

    difference=$((time_now - time_line))
    
  • You could also directly use it in your if statement instead of saving to a variable at all:

    if [ $((time_now - time_line)) -ge 2592000 ]
    

You must log in to answer this question.

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