Get the newest directory in bash to a variables

后端 未结 8 2075
北恋
北恋 2020-12-13 13:17

I would like to find the newest sub directory in a directory and save the result to variable in bash.

Something like this:

ls -t /backups | head -1 &         


        
8条回答
  •  旧巷少年郎
    2020-12-13 13:55

    With GNU find you can get list of directories with modification timestamps, sort that list and output the newest:

    find . -mindepth 1 -maxdepth 1 -type d -printf "%T@\t%p\0" | sort -z -n | cut -z -f2- | tail -z -n1
    

    or newline separated

    find . -mindepth 1 -maxdepth 1 -type d -printf "%T@\t%p\n" | sort -n | cut -f2- | tail -n1
    

    With POSIX find (that does not have -printf) you may, if you have it, run stat to get file modification timestamp:

    find . -mindepth 1 -maxdepth 1 -type d -exec stat -c '%Y %n' {} \; | sort -n | cut -d' ' -f2- | tail -n1
    

    Without stat a pure shell solution may be used by replacing [[ bash extension with [ as in this answer.

提交回复
热议问题