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

前端 未结 6 870
渐次进展
渐次进展 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 13:08

    You can do that in bash in a single statement like so:

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

    You can also remove that newline without echo:

    ls -t |head -n1 |tr -d '\n'
    

    Make sure ls doesn't output colors to non-tty streams (i.e. specify color by ls --color=never or ls --color=auto or not at all).

    The ls solution will output files of any kind sorted by modification time. If you want only regular files or if you don't want directories then you can use find and xargs:

    echo -n "newest file: $(find . -maxdepth 1 -type f -print0 |xargs -0 ls -t)"
    

提交回复
热议问题