How do I get the name of the newest file via the Terminal?

前端 未结 6 867
渐次进展
渐次进展 2021-01-12 12:29

I\'m trying to create a macro for Keyboard Maestro for OS X doing the following:

  1. Get name of newest file in a directory on my disk based on date created;
6条回答
  •  抹茶落季
    2021-01-12 12:54

    You can't do it with only ls. However, as echo is generally built into the shell, it doesn't really add any overhead into the script. To get just the name of the file, I'd suggest:

    echo -n "newest: $(ls -t1 | head -n1)"
    

    If, for some reason, you really want to eliminate the head, then I suppose you could go for something like:

    ls -t1 | ( read n; echo -n "newest: $n")
    

    (read is built into the shell, head isn't.)

    Note that these solutions do not recurse into subdirectories, since that was not specified in the question. In fact, subdirectories may be printed as the newest "file".

提交回复
热议问题