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.
Touch command is used to change these timestamps (access time, modification time, and change time of a file).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With