6

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.

2 Answers 2

9

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

8
  • --time=atime does not set the sorting order; it just sets the time to the access time (rather than modification time) of the file. To actually sort by this time, add --sort=t.
    – Jos
    Oct 4, 2016 at 9:36
  • @Jos good catch, thanks :-) I edited my answer.
    – Wayne_Yux
    Oct 4, 2016 at 9:38
  • It is true according to man ls but I can't reproduce it using read-only access to a file.
    – Jos
    Oct 4, 2016 at 9:38
  • I think that you will get the same result with ls -ltr --time=atime
    – Katu
    Oct 4, 2016 at 9:45
  • 1
    @Jos I just tested it by playing with touch -a and some ls commands
    – Wayne_Yux
    Oct 4, 2016 at 10:05
5

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 (precisely relatime) in Epoch as first column, and filename as next

  • sort -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-
3
  • what to add in command if I want the time of file when it was accessed. Oct 4, 2016 at 10:04
  • @Avanibadheka Check my edits.
    – heemayl
    Oct 4, 2016 at 10:27
  • working well , upvoted . Oct 4, 2016 at 10:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .