Quote:
Originally Posted by casperdaghost
Code:
for i in $(ls -ltr /var/ftp/)
|
Do not use
ls this way to obtain file lists; the output varies by locale. If you are only using it to produce interesting strings for testing, then that is okay, but if you intend to parse the output in any way, DON'T.
If you want a list of files in a directory (or directory tree) sorted by last modification time, oldest last, use something like the following in Bash:
Code:
export LANG=C LC_ALL=C
IFS=$'\t'
while read -rd "" year month day hour min sec filename ; do
# To get integer seconds, use "${sec%%.*}" instead of "$sec".
echo "$year-$month-$day+$hour:$min:$sec" "$filename"
done < <( find DIR(s) -maxdepth 1 -type f -printf '%TY\t%Tm\t%Td\t%TH\t%TM\t%TS\t%p\0' | sort -rz )
If you want files in subdirectories too, just drop the
-maxdepth 1 option. To get oldest first, use
sort -z . If you want the times in UTC instead of local time, add
export TZ=UTC at the start. You can also access other metadata on the files, like owner, group, size, access mode and so on; see
find format directives for details.
This construct uses ASCII NULs as separators. It means all possible file names will work correctly; even the truly strange ones that have newlines or whatnot. Using the C locale as shown, this is guaranteed to handle all file names correctly in Linux.