How can I list files in reverse time order by a command and pass them as arguments to another command? ...

Does a random sequence of vectors span a Hilbert space?

How does the body cool itself in a stillsuit?

Getting representations of the Lie group out of representations of its Lie algebra

Do i imagine the linear (straight line) homotopy in a correct way?

Why does BitLocker not use RSA?

3D Masyu - A Die

What is the proper term for etching or digging of wall to hide conduit of cables

How many time has Arya actually used Needle?

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

How to resize main filesystem

Short story about astronauts fertilizing soil with their own bodies

Was the pager message from Nick Fury to Captain Marvel unnecessary?

NIntegrate on a solution of a matrix ODE

Did John Wesley plagiarize Matthew Henry...?

Did pre-Columbian Americans know the spherical shape of the Earth?

Plotting a Maclaurin series

What is "Lambda" in Heston's original paper on stochastic volatility models?

Sally's older brother

Besides transaction validation, are there any other uses of the Script language in Bitcoin

New Order #6: Easter Egg

The Nth Gryphon Number

Can gravitational waves pass through a black hole?

Fit odd number of triplets in a measure?

What is a more techy Technical Writer job title that isn't cutesy or confusing?



How can I list files in reverse time order by a command and pass them as arguments to another command?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionbash command to create array with the 10 most recent images in a dir?Print shell arguments in reverse orderShow sum of file sizes in directory listingbash how to remove options from parameters after processingrefreshing terminal window's view of a recreated directoryGroup lines in a file and feed a group to a program at a timeHow to pass files found by find as arguments?Create variable based on the order a file is in an alphabetical list of filesExpand glob with flag inserted before each filenameWhere shall we place the commands for parsing command line arguments in a script?Reverse the order of file matching as arguments





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2















I have a program which takes in some files as arguments in one command line. I would like to invoke it with all the files in a directory listed in reverse time order.



For example:



I have following files in reverse time order in a directory



$ ls -tr
Introduction.pdf 'Object-Oriented Data Model.pdf'


I can run my program straightforward,



myprogram Introduction.pdf  'Object-Oriented Data Model.pdf' 


but I want to do the file listing by another command. This won't work because of the space in one file's name:



myprogram $(ls -tr)


I remember parsing ls output is not a good practice. I am not sure if find can help.



What can I do then?



Thanks.










share|improve this question































    2















    I have a program which takes in some files as arguments in one command line. I would like to invoke it with all the files in a directory listed in reverse time order.



    For example:



    I have following files in reverse time order in a directory



    $ ls -tr
    Introduction.pdf 'Object-Oriented Data Model.pdf'


    I can run my program straightforward,



    myprogram Introduction.pdf  'Object-Oriented Data Model.pdf' 


    but I want to do the file listing by another command. This won't work because of the space in one file's name:



    myprogram $(ls -tr)


    I remember parsing ls output is not a good practice. I am not sure if find can help.



    What can I do then?



    Thanks.










    share|improve this question



























      2












      2








      2


      1






      I have a program which takes in some files as arguments in one command line. I would like to invoke it with all the files in a directory listed in reverse time order.



      For example:



      I have following files in reverse time order in a directory



      $ ls -tr
      Introduction.pdf 'Object-Oriented Data Model.pdf'


      I can run my program straightforward,



      myprogram Introduction.pdf  'Object-Oriented Data Model.pdf' 


      but I want to do the file listing by another command. This won't work because of the space in one file's name:



      myprogram $(ls -tr)


      I remember parsing ls output is not a good practice. I am not sure if find can help.



      What can I do then?



      Thanks.










      share|improve this question
















      I have a program which takes in some files as arguments in one command line. I would like to invoke it with all the files in a directory listed in reverse time order.



      For example:



      I have following files in reverse time order in a directory



      $ ls -tr
      Introduction.pdf 'Object-Oriented Data Model.pdf'


      I can run my program straightforward,



      myprogram Introduction.pdf  'Object-Oriented Data Model.pdf' 


      but I want to do the file listing by another command. This won't work because of the space in one file's name:



      myprogram $(ls -tr)


      I remember parsing ls output is not a good practice. I am not sure if find can help.



      What can I do then?



      Thanks.







      bash






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 8 hours ago







      Tim

















      asked 9 hours ago









      TimTim

      28.9k79270495




      28.9k79270495






















          3 Answers
          3






          active

          oldest

          votes


















          2














          If you've got reasonably up-to-date versions of the GNU utilities you can have them handle NULL-terminated data. This allows one to construct pipelines that are not affected by whitespace or newlines in the data itself.



          My test tool is a quick script called /tmp/args:



          #!/bin/bash
          echo "This is args with $# value(s)"
          for f in "$@"; do echo "> $f <"; done


          This is how you can feed it a series of filenames on the command line, sorted by file time last modified:



          find -type f -printf "%T@ %p" | sort -z | sed -z 's/^[0-9.]* //' | xargs -0 /tmp/args


          The find command prefixes each file/path name with a representation in fractional seconds of the date/time last modified. This is handled by sort to order from lowest (oldest) to highest (newest). The sed strips off the leading number we've just used to sort by, and the resulting set of filenames are passed to xargs. Replace the %p with %P if you prefer to omit the leading ./ from filenames.



          Example data



          # "c d" contains a space; "e f" contains a newline; "h" has leading whitespace
          touch a 'e
          f' g ' h ' 'c d' b


          Example result



          This is args with 6 value(s)
          > ./a <
          > ./e
          f <
          > ./g <
          > ./ h <
          > ./c d <
          > ./b <





          share|improve this answer































            1














            (IFS=$'n'; set -f; your_program $(ls -tr))


            Assuming that the filenames don't contain newlines.



            Example:



            % touch 'a   b'
            % touch 'c d'
            % touch '*'
            % (IFS=$'n'; set -f; printf '%sn' $(ls -tr))
            e f
            a b
            c d
            *


            Variant for a standard shell which doesn't support $'...' strings:



            (IFS='
            ' ; set -f; your_program $(ls -tr))




            Simple python wrapper which will work even with filenames containing newlines. Usage can be this_wrapper your_program *.



            #! /usr/bin/python
            import os
            import sys

            sys.argv[2:] = sorted(sys.argv[2:], key=os.path.getmtime)
            os.execvp(sys.argv[1], sys.argv[1:])





            share|improve this answer


























            • Thanks. What if the filenames contains newlines

              – Tim
              9 hours ago











            • Then this won't work ;-) -- and you'll have to use something like perl or python.

              – Uncle Billy
              9 hours ago











            • Thanks. How will you use Python?

              – Tim
              9 hours ago






            • 1





              I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

              – Uncle Billy
              8 hours ago






            • 1





              @Freddy Rarely. But everything is possible.

              – Tim
              7 hours ago





















            1














            Bash doesn't yet make it easy to sort files by modification time, so here's the obligatory zsh-based answer. You don't have to switch to zsh as your login shell in order to use its features.



            Here I set up a wrapper function that expects either one or two arguments; the first argument is the program to execute (e.g. myprogram); the second, optional, argument is the directory containing the files that you want to pass to the program. If you don't specify a second argument, it defaults to the current directory.



            zeio() {
            # Zsh-based Execute with files In Order
            [ -d "${2:-.}" ] || return
            zsh -c "$1 "${2:-.}"/*(.Om)"
            }


            Name it whatever you like, of course. After a quick sanity-check of the second argument (again, defaulting to ., the current directory), we call zsh with a single double-quoted string that contains the program (argument #1) and the directory (argument #2) -- defaulting to . -- with a wildcard / glob expansion that has two "glob qualifiers" in the trailing parenthesis:





            1. . -- must be regular files (not directories or symlinks, etc)


            2. Om -- Order (sort) the resulting list by modification time, earliest first


            It's that Om glob qualifier that does all of the real work here.



            Here's some sample runs; myprog is a simple shell script to demonstrate the arguments it receives, in order:



            #!/bin/sh
            for arg do
            printf 'Arg: ->%s<-n' "$arg"
            done


            and go.sh is the file where I saved the function. The rest of the directory structure is:



            $ tree .
            .
            ├── dir1
            │   ├── 203142
            │   ├── 203143
            │   └── 203144
            ├── dir3
            │   ├── first12filename
            │   ├── this is 3rd
            │   └── this is second
            ├── dir two
            │   ├── 203225
            │   ├── 203226
            │   └── 203227
            ├── go.sh
            └── myprog


            ... where I've created the sets of three files in each subdirectory in the listed sequence; I expect to see them in this same order when I execute the function. The first filename under dir3 has a newline in it, represented by tree with 12. The results are:



            Demonstrating the default-to-current-directory behavior:



            $ zeio ./myprog
            Arg: ->./myprog<-
            Arg: ->./go.sh<-


            Normal filename demonstration



            $ zeio ./myprog dir1
            Arg: ->dir1/203142<-
            Arg: ->dir1/203143<-
            Arg: ->dir1/203144<-


            Directory has a space in it



            $ zeio ./myprog "dir two"
            Arg: ->dir two/203225<-
            Arg: ->dir two/203226<-
            Arg: ->dir two/203227<-


            filenames have whitespace in them



            $ zeio ./myprog dir3
            Arg: ->dir3/first
            filename<-
            Arg: ->dir3/this is second<-
            Arg: ->dir3/this is 3rd<-





            share|improve this answer
























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "106"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f513695%2fhow-can-i-list-files-in-reverse-time-order-by-a-command-and-pass-them-as-argumen%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              If you've got reasonably up-to-date versions of the GNU utilities you can have them handle NULL-terminated data. This allows one to construct pipelines that are not affected by whitespace or newlines in the data itself.



              My test tool is a quick script called /tmp/args:



              #!/bin/bash
              echo "This is args with $# value(s)"
              for f in "$@"; do echo "> $f <"; done


              This is how you can feed it a series of filenames on the command line, sorted by file time last modified:



              find -type f -printf "%T@ %p" | sort -z | sed -z 's/^[0-9.]* //' | xargs -0 /tmp/args


              The find command prefixes each file/path name with a representation in fractional seconds of the date/time last modified. This is handled by sort to order from lowest (oldest) to highest (newest). The sed strips off the leading number we've just used to sort by, and the resulting set of filenames are passed to xargs. Replace the %p with %P if you prefer to omit the leading ./ from filenames.



              Example data



              # "c d" contains a space; "e f" contains a newline; "h" has leading whitespace
              touch a 'e
              f' g ' h ' 'c d' b


              Example result



              This is args with 6 value(s)
              > ./a <
              > ./e
              f <
              > ./g <
              > ./ h <
              > ./c d <
              > ./b <





              share|improve this answer




























                2














                If you've got reasonably up-to-date versions of the GNU utilities you can have them handle NULL-terminated data. This allows one to construct pipelines that are not affected by whitespace or newlines in the data itself.



                My test tool is a quick script called /tmp/args:



                #!/bin/bash
                echo "This is args with $# value(s)"
                for f in "$@"; do echo "> $f <"; done


                This is how you can feed it a series of filenames on the command line, sorted by file time last modified:



                find -type f -printf "%T@ %p" | sort -z | sed -z 's/^[0-9.]* //' | xargs -0 /tmp/args


                The find command prefixes each file/path name with a representation in fractional seconds of the date/time last modified. This is handled by sort to order from lowest (oldest) to highest (newest). The sed strips off the leading number we've just used to sort by, and the resulting set of filenames are passed to xargs. Replace the %p with %P if you prefer to omit the leading ./ from filenames.



                Example data



                # "c d" contains a space; "e f" contains a newline; "h" has leading whitespace
                touch a 'e
                f' g ' h ' 'c d' b


                Example result



                This is args with 6 value(s)
                > ./a <
                > ./e
                f <
                > ./g <
                > ./ h <
                > ./c d <
                > ./b <





                share|improve this answer


























                  2












                  2








                  2







                  If you've got reasonably up-to-date versions of the GNU utilities you can have them handle NULL-terminated data. This allows one to construct pipelines that are not affected by whitespace or newlines in the data itself.



                  My test tool is a quick script called /tmp/args:



                  #!/bin/bash
                  echo "This is args with $# value(s)"
                  for f in "$@"; do echo "> $f <"; done


                  This is how you can feed it a series of filenames on the command line, sorted by file time last modified:



                  find -type f -printf "%T@ %p" | sort -z | sed -z 's/^[0-9.]* //' | xargs -0 /tmp/args


                  The find command prefixes each file/path name with a representation in fractional seconds of the date/time last modified. This is handled by sort to order from lowest (oldest) to highest (newest). The sed strips off the leading number we've just used to sort by, and the resulting set of filenames are passed to xargs. Replace the %p with %P if you prefer to omit the leading ./ from filenames.



                  Example data



                  # "c d" contains a space; "e f" contains a newline; "h" has leading whitespace
                  touch a 'e
                  f' g ' h ' 'c d' b


                  Example result



                  This is args with 6 value(s)
                  > ./a <
                  > ./e
                  f <
                  > ./g <
                  > ./ h <
                  > ./c d <
                  > ./b <





                  share|improve this answer













                  If you've got reasonably up-to-date versions of the GNU utilities you can have them handle NULL-terminated data. This allows one to construct pipelines that are not affected by whitespace or newlines in the data itself.



                  My test tool is a quick script called /tmp/args:



                  #!/bin/bash
                  echo "This is args with $# value(s)"
                  for f in "$@"; do echo "> $f <"; done


                  This is how you can feed it a series of filenames on the command line, sorted by file time last modified:



                  find -type f -printf "%T@ %p" | sort -z | sed -z 's/^[0-9.]* //' | xargs -0 /tmp/args


                  The find command prefixes each file/path name with a representation in fractional seconds of the date/time last modified. This is handled by sort to order from lowest (oldest) to highest (newest). The sed strips off the leading number we've just used to sort by, and the resulting set of filenames are passed to xargs. Replace the %p with %P if you prefer to omit the leading ./ from filenames.



                  Example data



                  # "c d" contains a space; "e f" contains a newline; "h" has leading whitespace
                  touch a 'e
                  f' g ' h ' 'c d' b


                  Example result



                  This is args with 6 value(s)
                  > ./a <
                  > ./e
                  f <
                  > ./g <
                  > ./ h <
                  > ./c d <
                  > ./b <






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  roaimaroaima

                  46.4k758124




                  46.4k758124

























                      1














                      (IFS=$'n'; set -f; your_program $(ls -tr))


                      Assuming that the filenames don't contain newlines.



                      Example:



                      % touch 'a   b'
                      % touch 'c d'
                      % touch '*'
                      % (IFS=$'n'; set -f; printf '%sn' $(ls -tr))
                      e f
                      a b
                      c d
                      *


                      Variant for a standard shell which doesn't support $'...' strings:



                      (IFS='
                      ' ; set -f; your_program $(ls -tr))




                      Simple python wrapper which will work even with filenames containing newlines. Usage can be this_wrapper your_program *.



                      #! /usr/bin/python
                      import os
                      import sys

                      sys.argv[2:] = sorted(sys.argv[2:], key=os.path.getmtime)
                      os.execvp(sys.argv[1], sys.argv[1:])





                      share|improve this answer


























                      • Thanks. What if the filenames contains newlines

                        – Tim
                        9 hours ago











                      • Then this won't work ;-) -- and you'll have to use something like perl or python.

                        – Uncle Billy
                        9 hours ago











                      • Thanks. How will you use Python?

                        – Tim
                        9 hours ago






                      • 1





                        I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                        – Uncle Billy
                        8 hours ago






                      • 1





                        @Freddy Rarely. But everything is possible.

                        – Tim
                        7 hours ago


















                      1














                      (IFS=$'n'; set -f; your_program $(ls -tr))


                      Assuming that the filenames don't contain newlines.



                      Example:



                      % touch 'a   b'
                      % touch 'c d'
                      % touch '*'
                      % (IFS=$'n'; set -f; printf '%sn' $(ls -tr))
                      e f
                      a b
                      c d
                      *


                      Variant for a standard shell which doesn't support $'...' strings:



                      (IFS='
                      ' ; set -f; your_program $(ls -tr))




                      Simple python wrapper which will work even with filenames containing newlines. Usage can be this_wrapper your_program *.



                      #! /usr/bin/python
                      import os
                      import sys

                      sys.argv[2:] = sorted(sys.argv[2:], key=os.path.getmtime)
                      os.execvp(sys.argv[1], sys.argv[1:])





                      share|improve this answer


























                      • Thanks. What if the filenames contains newlines

                        – Tim
                        9 hours ago











                      • Then this won't work ;-) -- and you'll have to use something like perl or python.

                        – Uncle Billy
                        9 hours ago











                      • Thanks. How will you use Python?

                        – Tim
                        9 hours ago






                      • 1





                        I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                        – Uncle Billy
                        8 hours ago






                      • 1





                        @Freddy Rarely. But everything is possible.

                        – Tim
                        7 hours ago
















                      1












                      1








                      1







                      (IFS=$'n'; set -f; your_program $(ls -tr))


                      Assuming that the filenames don't contain newlines.



                      Example:



                      % touch 'a   b'
                      % touch 'c d'
                      % touch '*'
                      % (IFS=$'n'; set -f; printf '%sn' $(ls -tr))
                      e f
                      a b
                      c d
                      *


                      Variant for a standard shell which doesn't support $'...' strings:



                      (IFS='
                      ' ; set -f; your_program $(ls -tr))




                      Simple python wrapper which will work even with filenames containing newlines. Usage can be this_wrapper your_program *.



                      #! /usr/bin/python
                      import os
                      import sys

                      sys.argv[2:] = sorted(sys.argv[2:], key=os.path.getmtime)
                      os.execvp(sys.argv[1], sys.argv[1:])





                      share|improve this answer















                      (IFS=$'n'; set -f; your_program $(ls -tr))


                      Assuming that the filenames don't contain newlines.



                      Example:



                      % touch 'a   b'
                      % touch 'c d'
                      % touch '*'
                      % (IFS=$'n'; set -f; printf '%sn' $(ls -tr))
                      e f
                      a b
                      c d
                      *


                      Variant for a standard shell which doesn't support $'...' strings:



                      (IFS='
                      ' ; set -f; your_program $(ls -tr))




                      Simple python wrapper which will work even with filenames containing newlines. Usage can be this_wrapper your_program *.



                      #! /usr/bin/python
                      import os
                      import sys

                      sys.argv[2:] = sorted(sys.argv[2:], key=os.path.getmtime)
                      os.execvp(sys.argv[1], sys.argv[1:])






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 6 hours ago

























                      answered 9 hours ago









                      Uncle BillyUncle Billy

                      9648




                      9648













                      • Thanks. What if the filenames contains newlines

                        – Tim
                        9 hours ago











                      • Then this won't work ;-) -- and you'll have to use something like perl or python.

                        – Uncle Billy
                        9 hours ago











                      • Thanks. How will you use Python?

                        – Tim
                        9 hours ago






                      • 1





                        I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                        – Uncle Billy
                        8 hours ago






                      • 1





                        @Freddy Rarely. But everything is possible.

                        – Tim
                        7 hours ago





















                      • Thanks. What if the filenames contains newlines

                        – Tim
                        9 hours ago











                      • Then this won't work ;-) -- and you'll have to use something like perl or python.

                        – Uncle Billy
                        9 hours ago











                      • Thanks. How will you use Python?

                        – Tim
                        9 hours ago






                      • 1





                        I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                        – Uncle Billy
                        8 hours ago






                      • 1





                        @Freddy Rarely. But everything is possible.

                        – Tim
                        7 hours ago



















                      Thanks. What if the filenames contains newlines

                      – Tim
                      9 hours ago





                      Thanks. What if the filenames contains newlines

                      – Tim
                      9 hours ago













                      Then this won't work ;-) -- and you'll have to use something like perl or python.

                      – Uncle Billy
                      9 hours ago





                      Then this won't work ;-) -- and you'll have to use something like perl or python.

                      – Uncle Billy
                      9 hours ago













                      Thanks. How will you use Python?

                      – Tim
                      9 hours ago





                      Thanks. How will you use Python?

                      – Tim
                      9 hours ago




                      1




                      1





                      I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                      – Uncle Billy
                      8 hours ago





                      I'm no python programmer, but since nobody steps in .... YMMV, that may not be the state of the art ;-)

                      – Uncle Billy
                      8 hours ago




                      1




                      1





                      @Freddy Rarely. But everything is possible.

                      – Tim
                      7 hours ago







                      @Freddy Rarely. But everything is possible.

                      – Tim
                      7 hours ago













                      1














                      Bash doesn't yet make it easy to sort files by modification time, so here's the obligatory zsh-based answer. You don't have to switch to zsh as your login shell in order to use its features.



                      Here I set up a wrapper function that expects either one or two arguments; the first argument is the program to execute (e.g. myprogram); the second, optional, argument is the directory containing the files that you want to pass to the program. If you don't specify a second argument, it defaults to the current directory.



                      zeio() {
                      # Zsh-based Execute with files In Order
                      [ -d "${2:-.}" ] || return
                      zsh -c "$1 "${2:-.}"/*(.Om)"
                      }


                      Name it whatever you like, of course. After a quick sanity-check of the second argument (again, defaulting to ., the current directory), we call zsh with a single double-quoted string that contains the program (argument #1) and the directory (argument #2) -- defaulting to . -- with a wildcard / glob expansion that has two "glob qualifiers" in the trailing parenthesis:





                      1. . -- must be regular files (not directories or symlinks, etc)


                      2. Om -- Order (sort) the resulting list by modification time, earliest first


                      It's that Om glob qualifier that does all of the real work here.



                      Here's some sample runs; myprog is a simple shell script to demonstrate the arguments it receives, in order:



                      #!/bin/sh
                      for arg do
                      printf 'Arg: ->%s<-n' "$arg"
                      done


                      and go.sh is the file where I saved the function. The rest of the directory structure is:



                      $ tree .
                      .
                      ├── dir1
                      │   ├── 203142
                      │   ├── 203143
                      │   └── 203144
                      ├── dir3
                      │   ├── first12filename
                      │   ├── this is 3rd
                      │   └── this is second
                      ├── dir two
                      │   ├── 203225
                      │   ├── 203226
                      │   └── 203227
                      ├── go.sh
                      └── myprog


                      ... where I've created the sets of three files in each subdirectory in the listed sequence; I expect to see them in this same order when I execute the function. The first filename under dir3 has a newline in it, represented by tree with 12. The results are:



                      Demonstrating the default-to-current-directory behavior:



                      $ zeio ./myprog
                      Arg: ->./myprog<-
                      Arg: ->./go.sh<-


                      Normal filename demonstration



                      $ zeio ./myprog dir1
                      Arg: ->dir1/203142<-
                      Arg: ->dir1/203143<-
                      Arg: ->dir1/203144<-


                      Directory has a space in it



                      $ zeio ./myprog "dir two"
                      Arg: ->dir two/203225<-
                      Arg: ->dir two/203226<-
                      Arg: ->dir two/203227<-


                      filenames have whitespace in them



                      $ zeio ./myprog dir3
                      Arg: ->dir3/first
                      filename<-
                      Arg: ->dir3/this is second<-
                      Arg: ->dir3/this is 3rd<-





                      share|improve this answer




























                        1














                        Bash doesn't yet make it easy to sort files by modification time, so here's the obligatory zsh-based answer. You don't have to switch to zsh as your login shell in order to use its features.



                        Here I set up a wrapper function that expects either one or two arguments; the first argument is the program to execute (e.g. myprogram); the second, optional, argument is the directory containing the files that you want to pass to the program. If you don't specify a second argument, it defaults to the current directory.



                        zeio() {
                        # Zsh-based Execute with files In Order
                        [ -d "${2:-.}" ] || return
                        zsh -c "$1 "${2:-.}"/*(.Om)"
                        }


                        Name it whatever you like, of course. After a quick sanity-check of the second argument (again, defaulting to ., the current directory), we call zsh with a single double-quoted string that contains the program (argument #1) and the directory (argument #2) -- defaulting to . -- with a wildcard / glob expansion that has two "glob qualifiers" in the trailing parenthesis:





                        1. . -- must be regular files (not directories or symlinks, etc)


                        2. Om -- Order (sort) the resulting list by modification time, earliest first


                        It's that Om glob qualifier that does all of the real work here.



                        Here's some sample runs; myprog is a simple shell script to demonstrate the arguments it receives, in order:



                        #!/bin/sh
                        for arg do
                        printf 'Arg: ->%s<-n' "$arg"
                        done


                        and go.sh is the file where I saved the function. The rest of the directory structure is:



                        $ tree .
                        .
                        ├── dir1
                        │   ├── 203142
                        │   ├── 203143
                        │   └── 203144
                        ├── dir3
                        │   ├── first12filename
                        │   ├── this is 3rd
                        │   └── this is second
                        ├── dir two
                        │   ├── 203225
                        │   ├── 203226
                        │   └── 203227
                        ├── go.sh
                        └── myprog


                        ... where I've created the sets of three files in each subdirectory in the listed sequence; I expect to see them in this same order when I execute the function. The first filename under dir3 has a newline in it, represented by tree with 12. The results are:



                        Demonstrating the default-to-current-directory behavior:



                        $ zeio ./myprog
                        Arg: ->./myprog<-
                        Arg: ->./go.sh<-


                        Normal filename demonstration



                        $ zeio ./myprog dir1
                        Arg: ->dir1/203142<-
                        Arg: ->dir1/203143<-
                        Arg: ->dir1/203144<-


                        Directory has a space in it



                        $ zeio ./myprog "dir two"
                        Arg: ->dir two/203225<-
                        Arg: ->dir two/203226<-
                        Arg: ->dir two/203227<-


                        filenames have whitespace in them



                        $ zeio ./myprog dir3
                        Arg: ->dir3/first
                        filename<-
                        Arg: ->dir3/this is second<-
                        Arg: ->dir3/this is 3rd<-





                        share|improve this answer


























                          1












                          1








                          1







                          Bash doesn't yet make it easy to sort files by modification time, so here's the obligatory zsh-based answer. You don't have to switch to zsh as your login shell in order to use its features.



                          Here I set up a wrapper function that expects either one or two arguments; the first argument is the program to execute (e.g. myprogram); the second, optional, argument is the directory containing the files that you want to pass to the program. If you don't specify a second argument, it defaults to the current directory.



                          zeio() {
                          # Zsh-based Execute with files In Order
                          [ -d "${2:-.}" ] || return
                          zsh -c "$1 "${2:-.}"/*(.Om)"
                          }


                          Name it whatever you like, of course. After a quick sanity-check of the second argument (again, defaulting to ., the current directory), we call zsh with a single double-quoted string that contains the program (argument #1) and the directory (argument #2) -- defaulting to . -- with a wildcard / glob expansion that has two "glob qualifiers" in the trailing parenthesis:





                          1. . -- must be regular files (not directories or symlinks, etc)


                          2. Om -- Order (sort) the resulting list by modification time, earliest first


                          It's that Om glob qualifier that does all of the real work here.



                          Here's some sample runs; myprog is a simple shell script to demonstrate the arguments it receives, in order:



                          #!/bin/sh
                          for arg do
                          printf 'Arg: ->%s<-n' "$arg"
                          done


                          and go.sh is the file where I saved the function. The rest of the directory structure is:



                          $ tree .
                          .
                          ├── dir1
                          │   ├── 203142
                          │   ├── 203143
                          │   └── 203144
                          ├── dir3
                          │   ├── first12filename
                          │   ├── this is 3rd
                          │   └── this is second
                          ├── dir two
                          │   ├── 203225
                          │   ├── 203226
                          │   └── 203227
                          ├── go.sh
                          └── myprog


                          ... where I've created the sets of three files in each subdirectory in the listed sequence; I expect to see them in this same order when I execute the function. The first filename under dir3 has a newline in it, represented by tree with 12. The results are:



                          Demonstrating the default-to-current-directory behavior:



                          $ zeio ./myprog
                          Arg: ->./myprog<-
                          Arg: ->./go.sh<-


                          Normal filename demonstration



                          $ zeio ./myprog dir1
                          Arg: ->dir1/203142<-
                          Arg: ->dir1/203143<-
                          Arg: ->dir1/203144<-


                          Directory has a space in it



                          $ zeio ./myprog "dir two"
                          Arg: ->dir two/203225<-
                          Arg: ->dir two/203226<-
                          Arg: ->dir two/203227<-


                          filenames have whitespace in them



                          $ zeio ./myprog dir3
                          Arg: ->dir3/first
                          filename<-
                          Arg: ->dir3/this is second<-
                          Arg: ->dir3/this is 3rd<-





                          share|improve this answer













                          Bash doesn't yet make it easy to sort files by modification time, so here's the obligatory zsh-based answer. You don't have to switch to zsh as your login shell in order to use its features.



                          Here I set up a wrapper function that expects either one or two arguments; the first argument is the program to execute (e.g. myprogram); the second, optional, argument is the directory containing the files that you want to pass to the program. If you don't specify a second argument, it defaults to the current directory.



                          zeio() {
                          # Zsh-based Execute with files In Order
                          [ -d "${2:-.}" ] || return
                          zsh -c "$1 "${2:-.}"/*(.Om)"
                          }


                          Name it whatever you like, of course. After a quick sanity-check of the second argument (again, defaulting to ., the current directory), we call zsh with a single double-quoted string that contains the program (argument #1) and the directory (argument #2) -- defaulting to . -- with a wildcard / glob expansion that has two "glob qualifiers" in the trailing parenthesis:





                          1. . -- must be regular files (not directories or symlinks, etc)


                          2. Om -- Order (sort) the resulting list by modification time, earliest first


                          It's that Om glob qualifier that does all of the real work here.



                          Here's some sample runs; myprog is a simple shell script to demonstrate the arguments it receives, in order:



                          #!/bin/sh
                          for arg do
                          printf 'Arg: ->%s<-n' "$arg"
                          done


                          and go.sh is the file where I saved the function. The rest of the directory structure is:



                          $ tree .
                          .
                          ├── dir1
                          │   ├── 203142
                          │   ├── 203143
                          │   └── 203144
                          ├── dir3
                          │   ├── first12filename
                          │   ├── this is 3rd
                          │   └── this is second
                          ├── dir two
                          │   ├── 203225
                          │   ├── 203226
                          │   └── 203227
                          ├── go.sh
                          └── myprog


                          ... where I've created the sets of three files in each subdirectory in the listed sequence; I expect to see them in this same order when I execute the function. The first filename under dir3 has a newline in it, represented by tree with 12. The results are:



                          Demonstrating the default-to-current-directory behavior:



                          $ zeio ./myprog
                          Arg: ->./myprog<-
                          Arg: ->./go.sh<-


                          Normal filename demonstration



                          $ zeio ./myprog dir1
                          Arg: ->dir1/203142<-
                          Arg: ->dir1/203143<-
                          Arg: ->dir1/203144<-


                          Directory has a space in it



                          $ zeio ./myprog "dir two"
                          Arg: ->dir two/203225<-
                          Arg: ->dir two/203226<-
                          Arg: ->dir two/203227<-


                          filenames have whitespace in them



                          $ zeio ./myprog dir3
                          Arg: ->dir3/first
                          filename<-
                          Arg: ->dir3/this is second<-
                          Arg: ->dir3/this is 3rd<-






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 3 hours ago









                          Jeff SchallerJeff Schaller

                          45.2k1164147




                          45.2k1164147






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Unix & Linux Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f513695%2fhow-can-i-list-files-in-reverse-time-order-by-a-command-and-pass-them-as-argumen%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Couldn't open a raw socket. Error: Permission denied (13) (nmap)Is it possible to run networking commands...

                              VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

                              Why not use the yoke to control yaw, as well as pitch and roll? Announcing the arrival of...