Skip to main content
added 410 characters in body
Source Link
glenn jackman
  • 88.6k
  • 16
  • 124
  • 179

You don't need to store the output in a variable at all:

cd /home/Downloads
command ls -t | head -20 | while read -r file; do
    ./cmd "$file"
done

or even

command ls -t | head -20 | xargs -L 1 ./cmd

A safer way to work this is with stat. It still doesn't protect you from filenames with newlines, but

stat -c "%Y %n" * | sort -rn | head -20 | cut -d" " -f2- | xargs -L 1 ./cmd

To be foolproof, find -- probably need GNU tools for the null-byte handling

find . "${find_options[@]}" -printf '%T@ %p\0' | 
sort -zrn |
xargs -0 -L 1 sh -c './cmd "$(echo "$0" | sed "1s/^[0-9.]\\+ //")"'

the find_options array can be used as a placeholder to add filtering directives, such as

find_options=( -type f )
find_options+=( -maxdepth 1 )
find_options+=( -name '*.txt' )

and so on

You don't need to store the output in a variable at all:

cd /home/Downloads
command ls -t | head -20 | while read -r file; do
    ./cmd "$file"
done

or even

command ls -t | head -20 | xargs -L 1 ./cmd

You don't need to store the output in a variable at all:

cd /home/Downloads
command ls -t | head -20 | while read -r file; do
    ./cmd "$file"
done

or even

command ls -t | head -20 | xargs -L 1 ./cmd

A safer way to work this is with stat. It still doesn't protect you from filenames with newlines, but

stat -c "%Y %n" * | sort -rn | head -20 | cut -d" " -f2- | xargs -L 1 ./cmd

To be foolproof, find -- probably need GNU tools for the null-byte handling

find . "${find_options[@]}" -printf '%T@ %p\0' | 
sort -zrn |
xargs -0 -L 1 sh -c './cmd "$(echo "$0" | sed "1s/^[0-9.]\\+ //")"'

the find_options array can be used as a placeholder to add filtering directives, such as

find_options=( -type f )
find_options+=( -maxdepth 1 )
find_options+=( -name '*.txt' )

and so on

Post Migrated Here from serverfault.com (revisions)
Source Link
glenn jackman
  • 88.6k
  • 16
  • 124
  • 179

You don't need to store the output in a variable at all:

cd /home/Downloads
command ls -t | head -20 | while read -r file; do
    ./cmd "$file"
done

or even

command ls -t | head -20 | xargs -L 1 ./cmd