Bash Comparing Time Stamps - bash

I have bash script, where I'm looking at the git log of a file, and basically if the timestamp in the file is greater than the minus time i've specified, then alert me via slack, this sort of works, but not on a file which has a much older time stamp, code below;
#!/bin/bash
#Variables
NOW=$(date +"%a %b%Oe %H:%M:%S %Y")
MINUS=$(date +"%a %b%Oe %H:%M:%S %Y" --date '-10 min')
VALUEFILES=("helm/components/admin-ui/values" "helm/components/cssr/values")
#should run every 20minutes to catch any changes - also, once a change has been detected, get the author of the change to also send to slack notification
#git clone
#git clone xxx
cd xxx
#testing
echo "Time now with time -10mins"
echo "$NOW"
echo "$MINUS"
echo `pwd`
##########################
#functions
check_time_stamp_values () {
for f in "${VALUEFILES[#]}"; do
git log -- "$f".yaml > "$f".txt
grep "Date" "$f".txt | awk 'NR==1{ print $2, $3, $4, $5, $6 }' > "$f"-time.txt
echo "===================================================="
read -r firstline<"$f"-time.txt
if [ "$firstline" \> "$MINUS" ]
then
cat "$f"-time.txt
echo "$f.yaml has changed within the last 10minutes - sending slack notification"
echo "===================================================="
else
echo "===================================================="
cat "$f"-time.txt
echo "$f.yaml has not changed in the last 10minutes - no action required"
echo "===================================================="
fi
done
}
##########################
For the above, i get the below output;
Tue Nov 1 17:34:10 2022
Tue Nov 1 17:24:10 2022
====================================================
====================================================
Tue Nov 1 17:23:48 2022
values.yaml has not changed in the last 10minutes - no action required
====================================================
====================================================
Wed Oct 26 11:27:15 2022
helm/components/cssr/values.yaml has changed within the last 10minutes
====================================================
Anyone have any suggestions ? Many thanks

Solved this issue by doing the following;
NOW=$(date +"%Y-%m-%d %H:%M:%S")
MINUS=$(date +"%Y-%m-%d %H:%M:%S" --date '-10 min')
Change how the date is displayed, and also changed how the git log is displayed;
git log --date=format:'%Y-%m-%d %H:%M:%S' "$f".yaml > "$f".txt
Now works fine without any issues.

Related

Equivalent output of PowerShell's get-date, but using bash [duplicate]

I have a date in this format: "27 JUN 2011" and I want to convert it to 20110627
Is it possible to do in bash?
#since this was yesterday
date -dyesterday +%Y%m%d
#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d
#assuming this is similar to yesterdays `date` question from you
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d
#going on #seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d
#or a method to read it from stdin
read -p " Get date >> " DATE; printf " AS YYYYMMDD format >> %s" `date
-d"$DATE" +%Y%m%d`
#which then outputs the following:
#Get date >> 27 june 2011
#AS YYYYMMDD format >> 20110627
#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash
#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line
More on Dates
note this only works on GNU date
I have read that:
Solaris version of date, which is unable
to support -d can be resolve with
replacing sunfreeware.com version of
date
On OSX, I'm using -f to specify the input format, -j to not attempt to set any date, and an output format specifier. For example:
$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y"
082215
Your example:
$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d
20110627
date -d "25 JUN 2011" +%Y%m%d
outputs
20110625
If you would like a bash function that works both on Mac OS X and Linux:
#
# Convert one date format to another
#
# Usage: convert_date_format <input_format> <date> <output_format>
#
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
convert_date_format() {
local INPUT_FORMAT="$1"
local INPUT_DATE="$2"
local OUTPUT_FORMAT="$3"
local UNAME=$(uname)
if [[ "$UNAME" == "Darwin" ]]; then
# Mac OS X
date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT"
elif [[ "$UNAME" == "Linux" ]]; then
# Linux
date -d "$INPUT_DATE" +"$OUTPUT_FORMAT"
else
# Unsupported system
echo "Unsupported system"
fi
}
# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10'
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
Just with bash:
convert_date () {
local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
local i
for (( i=0; i<11; i++ )); do
[[ $2 = ${months[$i]} ]] && break
done
printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}
And invoke it like this
d=$( convert_date 27 JUN 2011 )
Or if the "old" date string is stored in a variable
d_old="27 JUN 2011"
d=$( convert_date $d_old ) # not quoted
It's enough to do:
data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206
If you want to add also the time you can use in that way
data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`
echo $data
Wed Feb 6 03:57:15 EST 2019
echo $datatime
20190206 03:57:15
Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d to get the same appearing result.

Declare date using awk

I need help in completing the below script in shell.
Requested format is to print previous, current and next business days (should exclude weekends and holidays).
text name : holiday.txt
#!/usr/bin/sh
cur_date=`date +"%A %m/%d/%Y"`
cur_day=`date +"%A"`
yesterday=`TZ=AEDT+13 date +"%A %m/%d/%Y"`;
twodd_back=`TZ=AEDT+37 date +"%A %m/%d/%Y"`;
tomorrow=`TZ=AEDT-35 date +"%A %m/%d/%Y"`;
twodd_later=`TZ=AEDT-59 date +"%A %m/%d/%Y"`;
cdate=`date +"%m/%d/%Y"`
####################
echo "Previous Business Day is $yesterday"
if echo $yesterday|awk '{print $1}'=Saturday
then echo "Previous Business Day is $twodd_back"
fi
echo "Current Business Day is $ cur_date"
echo " Next Business Day is $tomorrow"
The script in its current status does not execute successfully. It fails with below error.
awk: syntax error at source line 1
context is
{print >>> $1}= <<< Saturday
awk: bailing out at source line 1
To fix it, change your if statement.
if [[ `echo $yesterday | awk '{print $1}'` = Saturday ]];

Return yesterday's date in shell script using awk or echo

I am sure there is a simple answer to this :
Why does the following not give me the date and time in a script? What should I use rather than awk? Awk works fine if I need to query files but I guess it is the wrong thing to use here..
Code :
$ySTD=$(date --date yesterday "+%Y-%m-%d") | awk '{print substr($1,1,10)}'
echo ${ySTD}
echo 'STD calculated from DATE - last 24 hrs data will be fetched'
${ySTM}=$(date --date yesterday "+%T")| awk '{print substr($1,1,5)}'
echo ${ySTM}
In the shell I get this when the script runs:
+ awk '{print substr($1,1,10)}'
++ date --date yesterday +%Y-%m-%d
+ =2014-07-03
logdat3: line 41: =2014-07-03: command not found
+ echo
+ echo 'STD calculated from DATE - last 24 hrs data will be fetched'
STD calculated from DATE - last 24 hrs data will be fetched
+ awk '{print substr($1,1,5)}'
++ date --date yesterday +%T
+ =11:33:34
logdat3: line 45: =11:33:34: command not found
+ echo
Many thanks in advance
You're rigth, no awk needed:
$ read ySTD ySTM < <(date --date yesterday "+%Y-%m-%d %T")
$ echo $ySTD
2014-07-03
$ echo $ySTM
12:16:37
Anyway , your original code fixed:
ySTD=$(date --date yesterday "+%Y-%m-%d")
echo ${ySTD}
echo 'STD calculated from DATE - last 24 hrs data will be fetched'
ySTM=$(date --date yesterday "+%T")
echo ${ySTM}
You don't need to get a substring.

Shell Script for Yesterdays Date

I have tried adding -d "yesterday" but I haven't had any luck getting it to work. Here is what I have for the whole script:
#! /bin/bash
saveDir="TJ"
dd=$(date +"%m-%d-%Y")
for file in *.csv ; do
saveName="${saveDir}/TJ ${dd}.csv"
cut -d',' -f2,14 "$file" > "$saveName"
done
how do I get dd to output yesterdays date instead of the current date?
EDIT: This is what I have now
#! /bin/bash
saveDir="TJ"
dd=$(date --date='yesterday' +'%m-%d-%Y')
for file in *.csv ; do
saveName="${saveDir}/TJ ${dd}.csv"
cut -d',' -f2,14 "$file" > "$saveName"
done
the above is saving the file as TJ .csv but I'm not sure what was done incorrectly
I think you want to use -
$ cat test.sh
#!/bin/bash
dd=$(date --date='yesterday' +'%m-%d-%Y')
echo $dd
$ ./test.sh
12-31-2013
or you could use
$ date -d '1 day ago' +'%m-%d-%Y'
12/31/2013
And for tomorrow -
$ date -d '1 day' +'%m-%d-%Y'
01/02/2014
or
$ date --date='tomorrow'
Thu Jan 2 21:25:00 EST 2014
Get today's date in seconds since epoch. Subtract 86400 to get to yesterday. Then convert yesterday to the string format you want.
today=`date +"%s"`
yesterday=`expr $today - 86400`
dd=`date --date="#${yesterday}" +"%m-%d-%Y"`
Try this
yday=$(date --date yesterday "+%d-%m-%Y")
echo $yday
And If you works in Linux
yday=$(date -d "-1 days" +"%d-%m-%Y")
echo $yday
I tried date -d "yesterday" +%m-%d-%Y on my Linux, it worked fine.
If you are on unix platform, you cannot use -d,
you can get yesterday's date using perl, this is how I do using perl
dd=$(perl -e '($a,$b,$c,$day,$mon,$year,$d,$e,$f) = localtime(time-86400);printf "%02d-%02d-%4d",$day, $mon+1, $year+1900')
echo $dd
01-01-2014
NewDate=`date +"%A %d %B %Y" --date="-1 day"`
echo $NewDate
this will give your yesterday's date (-1)
This will give you tomorrow's date (+1)
even you can check for any values like (+/-) days

YYYY-MM-DD format date in shell script

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format.
How do I get this?
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
man date
Try: $(date +%F)
The %F option is an alias for %Y-%m-%d
You can do something like this:
$ date +'%Y-%m-%d'
$(date +%F)
output
2018-06-20
Or if you also want time:
$(date +%F_%H-%M-%S)
can be used to remove colons (:) in between
output
2018-06-20_09-55-58
You're looking for ISO 8601 standard date format, so if you have GNU date (or any date command more modern than 1988) just do: $(date -I)
date -d '1 hour ago' '+%Y-%m-%d'
The output would be 2015-06-14.
With recent Bash (version ≥ 4.2), you can use the builtin printf with the format modifier %(strftime_format)T:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf is much faster than date since it's a Bash builtin while date is an external command.
As well, printf -v date ... is faster than date=$(printf ...) since it doesn't require forking a subshell.
I use the following formulation:
TODAY=`date -I`
echo $TODAY
Checkout the man page for date, there is a number of other useful options:
man date
if you want the year in a two number format such as 17 rather than 2017, do the following:
DATE=`date +%d-%m-%y`
I use $(date +"%Y-%m-%d") or $(date +"%Y-%m-%d %T") with time and hours.
I used below method. Thanks for all methods/answers
ubuntu#apj:/tmp$ datevar=$(date +'%Y-%m-%d : %H-%M')
ubuntu#apj:/tmp$ echo $datevar
2022-03-31 : 10-48
Whenever I have a task like this I end up falling back to
$ man strftime
to remind myself of all the possibilities for time formatting options.
Try to use this command :
date | cut -d " " -f2-4 | tr " " "-"
The output would be like: 21-Feb-2021
#!/bin/bash -e
x='2018-01-18 10:00:00'
a=$(date -d "$x")
b=$(date -d "$a 10 min" "+%Y-%m-%d %H:%M:%S")
c=$(date -d "$b 10 min" "+%Y-%m-%d %H:%M:%S")
#date -d "$a 30 min" "+%Y-%m-%d %H:%M:%S"
echo Entered Date is $x
echo Second Date is $b
echo Third Date is $c
Here x is sample date used & then example displays both formatting of data as well as getting dates 10 mins more then current date.
You can set date as environment variable and later u can use it
setenv DATE `date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
or
DATE =`date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
echo "`date "+%F"`"
Will print YYYY-MM-DD
Try this code for a simple human readable timestamp:
dt=$(date)
echo $dt
Output:
Tue May 3 08:48:47 IST 2022

Resources