Can somebody tell me what am I doing wrong in following shell function?
NOTES_PATH=\"/home/temp\"
function open_note {
local files=()
The original code had several bugs:
xargs -0
were lost, because the output of ls -t
was not NUL-delimited.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.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:
<epoch time> <filename><NUL>
...which sort
then sorts on, after which the while read
loop discards the first part of each field.
A few other notes:
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.