I\'m trying to write a script that will display the name of oldest file within the directory that the script is executed from.
This is what I have so far:
The ls program has an option to sort on time and you can just grab the last file from that output::
# These are both "wun", not "ell".
# v v
oldest="$(ls -1t | tail -1)"
If you want to avoid directories, you can strip them out beforehand:
# This one's an "ell", this is still a "wun".
v v
oldest="$(ls -lt | grep -v '^d' | tail -1 | awk '{print $NF}')"
I wouldn't normally advocate parsing ls output but it's fine for quick and dirty jobs, and if you understand its limitations.
If you want a script that will work even for crazies who insist on putting control characters in their file names :-) then this page has some better options, including:
unset -v oldest
for file in "$dir"/*; do
[[ -z $oldest || $file -ot $oldest ]] && oldest=$file
done
Though I'd suggest following that link to understand why ls parsing is considered a bad idea generally (and hence why it can be useful in limited circumstances such as when you can guarantee all your files are of the YYYY-MM-DD.log variety for example). There's a font of useful information over there.