how to write a shell script that print the last modified file ?

Hi guys,

-could any one help me with this (I'm new to UNIX)

how to write a shell script that tell me the last modified file in the current directory?
so if I run the script in a diferent directory,will work.
and can I write the script by C++ language and run it in the shell ?

I tried

ls -alst

but I couldn't save the first one (which is the last modified) in a $M

also I tried to use

tcgrep -t

but I couldn't,coz I have no idea about it :frowning:

I'll be thankfull if any one help,and I promise that I'll be helpfull member when I start understanding UNIX :smiley:

how about:

ls -1 -tr /path/to/dir | tail -1

it's works with directories ,not files
this one
ls -alst
works good for me ,it's works when I write
ls -alst | tail -1 and gives me the the first file
but it doesn't work when
ls -alst | head -1
coz I need the last modified one

Not really sure what you think the problem is. The solution provided by Yogesh is good. If you incorporate the following in a script:

ls -1rt | tail -1

it will provide you with the last modified file. Note that in the "ls" command that it is the numeral 1 following the hyphen.

If you need to remove directories from the listing, something like this perhaps.

ls -salt | sed '/^total/d;/^ *[1-9][0-9]* d/d;q'

The sed script is shorthand for grep -v '^total' | grep -v '^ *[1-9][0-9]* d' | head -1 -- combining those into a single script is somewhat more elegant IMHO, but the pipeline with multiple greps and a head will work fine as well. The first grep is to remove the "total 12345" printed on the first line, and the second grep is to remove any directories; the regular expression matches beginning of line, followed by optional spaces, followed by a number (this is what ls prints with the -s option on my system) followed by a space and a d which indicates that the entry is a directory. Without the -s option, you would simply remove any line with d as its first character; that's grep -v '^d'

thanks for help :slight_smile: