user3165241
user3165241

Reputation: 23

How to display the date value assigned variable outside the loop in shell script

I following code, I am reading a file from reverse order and comparing the dates,In side the if condition I am trying to assign the date value in one variable.In the 'if' condition value is displaying properly. If I am trying to display the variable out side the loop, value is not displaying.

previousDay=`date +"%Y-%m-%d" -d "-1 day"`
tac logfile.txt |
(
while read line
do
finish_time=`echo $line | sed -e 's/\([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\).*/\1/'`
file_content_date=`date -d "$finish_time" +%Y%m%d`
comparison_prev_date=`date -d "$previousDay" +%Y%m%d`
if [ $comparison_prev_date -ge $file_content_date ]; then
comparison_end_date=`date -d "$file_content_date" +%Y%m%d`
break
fi
done
)
echo $comparison_end_date

Upvotes: 1

Views: 248

Answers (1)

John1024
John1024

Reputation: 113934

Your while loop is in a subshell. That means that none of the environment variables created there are available to the main shell. Try:

#!/bin/bash
previousDay=`date +"%Y-%m-%d" -d "-1 day"`
while read line
do
    finish_time=`echo $line | sed -e 's/\([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\).*/\1/'`
    file_content_date=`date -d "$finish_time" +%Y%m%d`
    comparison_prev_date=`date -d "$previousDay" +%Y%m%d`
    if [ $comparison_prev_date -ge $file_content_date ]; then
        comparison_end_date=`date -d "$file_content_date" +%Y%m%d`
        break
    fi
done < <(tac logfile.txt)

echo $comparison_end_date

This code still provides tac logfile.txt as stdin to the while loop but it does it without creating a subshell.

The above requires both bash and an operating system, such as linux, that supports FIFOs.

MORE: Lacking those two requirements, one can use temporary files:

#!/bin/sh
previousDay=`date +"%Y-%m-%d" -d "-1 day"`
tmpfile=$HOME/.deleteme$$
trap 'rm "$tmpfile"' EXIT
tac logfile.txt >"$tmpfile"
while read line
do
    finish_time=`echo $line | sed -e 's/\([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\).*/\1/'`
    file_content_date=`date -d "$finish_time" +%Y%m%d`
    comparison_prev_date=`date -d "$previousDay" +%Y%m%d`
    if [ $comparison_prev_date -ge $file_content_date ]; then
        comparison_end_date=`date -d "$file_content_date" +%Y%m%d`
        break
    fi
done <"$tmpfile"

echo $comparison_end_date

Upvotes: 1

Related Questions