Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix command (other than 'stat' and 'ls') to get file modification date without parsing

I am writing a shell script in which I have to find the last modification date of a file.

Stat command is not available in my environment.

So i am using 'ls' as below to get desired result.

ls -l filename | awk '{print $6 $7 $8}'

But I have read in many forums that parsing ls is generally considered bad practise. While it (probably) works fine most of time, it's not guaranteed to work everytime.

Is there any other way to get file modification date in shell script.

like image 808
AnonGeek Avatar asked Jun 26 '12 21:06

AnonGeek


People also ask

Which command is used to change the modified time of file without altering it?

Touch command is used to change these timestamps (access time, modification time, and change time of a file).


1 Answers

How about using the find command?

e.g.,

 $ find filenname -maxdepth 0 -printf "%TY-%Tm-%Td %TH:%TM\n"

This particular format string gives output like this: 2012-06-13 00:05.

The find man page shows the formatting directives you can use with printf to tailor the output to what you need/want. Section -printf format contains all the details.

Compare ls output to find:

$ ls -l uname.txt | awk '{print  $6 , "", $7}'
2012-06-13  00:05

$ find uname.txt -maxdepth 0 -printf "%TY-%Tm-%Td %TH:%TM\n"
2012-06-13 00:05

Of course you can write scripts in any number of languages such a Python or Perl etc, to get the same information, however asking for a "unix command" sounded as if you were looking for a "built-in" shell command.

EDIT:

You could also inovke Python from the command line like this:

$ python -c "import os,time; print time.ctime(os.path.getmtime('uname.txt'))"

or if combined with other shell commands:

$ echo 'uname.txt' | xargs python -c "import os,time,sys; print time.ctime(os.path.getmtime(sys.argv[1]))"

both return: Wed Jun 13 00:05:29 2012

like image 196
Levon Avatar answered Nov 15 '22 18:11

Levon