How do I get the name of latest file?

1) How do I get the name of latest file in a variable?

2) Is it safe to delete all files from a dir

I am doing

cd $dir_name

if return_code > 0 
   rm \*
fi

what are other alternates to delete all files from a dir in a shell script?

:slight_smile:

answering #1

ls -ltr | tail -1

will give you all info on the most recent file in the current folder

ls -ltr | tail -1 | awk '{print $9}'

will give you just the filename

MYFILE=`ls -ltr | tail -1 | awk '{print $9}'`

will put that filename into $MYFILE

for #2
normally not best to cd then rm, better to

rm \dir\folder\*

or similar.
Seen too many examples where the cd failed, and then all files were deleted or some other command executed.

Yes, deleting all files from a directory is safe... until you inadvertently hit a system directory and your config/essential programs go bye-bye.
To get the newest file, issue a VAR=`ls -tr1|head -n 1`

Thanks

:slight_smile:

tail not needed

just this would do

ls -lrt | awk 'END{print $9 }'
To print the last field of last line
$ ls -lrt | awk '{ f=$NF }; END{ print f }'

This also works sometime
$ ls -t1 | head -n1