Find files in current directory sorted by modified time and store result in an array

前端 未结 1 805
借酒劲吻你
借酒劲吻你 2021-01-21 16:10

Can somebody tell me what am I doing wrong in following shell function?

NOTES_PATH=\"/home/temp\"

function open_note {

    local files=()                               


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 16:37

    The original code had several bugs:

    • The advantages of NUL-delimiting content prior to xargs -0 were lost, because the output of ls -t was not NUL-delimited.
    • Because xargs split results into multiple ls -t invocations, sorting took place only within these batches: Given enough filenames to require two or more invocations, those invocations would only be individually sorted, not globally sorted.
    • Parsing output of ls is generally error-prone.

    A cleaner implementation (assuming GNU find and GNU sort) would look like the following:

    open_note() {
      local filename mtime
      local -a files=( )
    
      while IFS= read -r -d' ' mtime && IFS= read -r -d '' filename; do
        files+=( "$filename" )
      done < <(find "$NOTES_PATH" -maxdepth 1 -type f -printf '%T@ %P\0' | sort -z -n)
    }
    

    The find action given emits a stream of the format:

     
    

    ...which sort then sorts on, after which the while read loop discards the first part of each field.


    A few other notes:

    • Don't use the function keyword; it makes your code gratuitously incompatible with POSIX sh, but (unlike other, more useful bashisms) adds no advantage whatsoever over the compliant syntax.
    • If you're trying to keep your locals scoped, be sure that you get all of them -- that includes names being looped over.

    0 讨论(0)
提交回复
热议问题