File list as per their usage
What do I do if I want the list of files from some specific directory, as per their usage?
That is, I want a list of files in ascending order as per their last usage with respect to time. In that case the file that was accessed last should be listed first.
Solution 1:
You can use
ls -l --time=atime --sort=t
Explanation:
-
ls -l
lists the files with the detailed list format -
--time=atime --sort=t
sets the sorting order to the time of the last access
Example:
$ touch foo bar foobar
$ ls -l
insgesamt 0
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 bar
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foo
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foobar
$ sleep 60; touch baz
$ ls -l
insgesamt 0
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 bar
-rw-r--r-- 1 Wayne users 0 Okt 4 11:58 baz
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foo
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foobar
After some minutes:
$ touch -a foo # sets atime to cuurent time
$ ls -lt
insgesamt 0
-rw-r--r-- 1 Wayne users 0 Okt 4 11:58 baz
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foobar
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 bar
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foo
$ ls -lt --time=atime
insgesamt 0
-rw-r--r-- 1 Wayne users 0 Okt 4 12:01 foo
-rw-r--r-- 1 Wayne users 0 Okt 4 11:58 baz
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 foobar
-rw-r--r-- 1 Wayne users 0 Okt 4 11:56 bar
Conclusion:
ls -lt --time=atime
does what you need
Solution 2:
Assuming no filename with newline in name, do:
stat -c '%X %n' * | sort -k1,1rn | cut -d' ' -f2-
stat -c '%X %n' *
prints the files in the current directory with access time (preciselyrelatime
) in Epoch as first column, and filename as nextsort -k1,1rn
sorts that by first field (time)cut -d' ' -f2-
gets the file name only
If you want to get the access time too along with the file name:
stat -c '%X %x %n' * | sort -k1,1rn | cut -d' ' -f2-