Aman Singh
Aman Singh

Reputation: 75

Linux | grep date informat "Aug 14"

I am writing a script where I need to do ls -l and grep files of today's date in "Aug 14" format. I assigned the date in a variable as dt=date "+%b %d" but I am not able to get the files.

In what way I can achieve that?

My script:

#!/bin/bash

#1st Argument i.e., $1 will be file name and 2nd Argument i.e., $2 will be directory path where file is located.

cd $2

command=`ls -l | grep $dt| grep $1`

if 

    [ -z "$command" ]; then

    echo "Critical : File $1 doesn't exists for $dt"
    exit 2


else

    echo "OK : File $1 exists for $dt"
    exit 0

fi

Running the script:

Upvotes: 1

Views: 399

Answers (2)

Aman Singh
Aman Singh

Reputation: 75

quoting the variable as below worked for me.

dt="date '+%b %d'"

Upvotes: 0

Dominique
Dominique

Reputation: 17565

I have the impression you need to do something, you have chosen a way to do it and you have problems implementing that way, leading you to this question.

You need to "list the files of today in the current directory".
As a way to do this, you have checked ls -l output and you want to render this, therefore you have formatted today's date as "Aug 14".
You seem to have problems with that rendering.

As mentioned by Cyrus, it's not a good idea to render ls results, so the way you have chosen is not good.

What's a better solution?

You might work with find, but as you are only interested in current directory, you need to limit the depth of the search (which you can achieve using -maxdepth), so I propose you following command (the -mtime -1 gives you the files, which have been modified at most one day ago):

find ./ -maxdepth 1 -mtime -1

Is this what you are looking for?

Edit:

A small extra as requested by Kvantour: you might use the mtime switch multiple times for searching for a date range, like the list of files, being changed at least one week, but less than two weeks ago, as follows:

find ./ -maxdepth 1 -mtime -14 -mtime +7

Upvotes: 1

Related Questions