Identify most recent directory in a directory.

After performing a shell script, a new directory is created and I need to work with that directory, but I don’t know the name.

How can I get the name of the most recent directory created?

The name will be formatted like 2022-12-01_1702, so the directory I need will be the last if sorted alphanumerically, if that helps.

I found resources for looking at files, but not directories. If it’s necessary to find this directory based on the creation date of its contents, there are files located at [dirname]/Databases/Filename.xxx

Thanks!

Is it the shell script also be triggered via ansible? If yes then you can register the path and work with it later. If not then do you know roughly when script be triggered then can just use shell command to find the directory with created date.

Use Ansible module *find* and sort the directories by *ctime*. For
example, given the tree

tree /tmp/test

/tmp/test
├── 2022-12-01_1701
├── 2022-12-01_1702
└── 2022-12-01_1703

Declare the variable

  last_dir: "{{ (out.files|sort(attribute='ctime')|last).path }}"

The tasks below

    - find:
        path: /tmp/test
        file_type: directory
      register: out
    - debug:
        var: last_dir

give

  last_dir: /tmp/test/2022-12-01_1703

If you want to take look at the *ctime*

  path_ctime: "{{ out.files|json_query('.[path, ctime]') }}"

give

  path_ctime:
    - [/tmp/test/2022-12-01_1702, 1669938403.313556]
    - [/tmp/test/2022-12-01_1701, 1669938401.2335565]
    - [/tmp/test/2022-12-01_1703, 1669938405.0495553]

Use Ansible module *find* and sort the directories by *ctime*. For
example, given the tree

This is only reliable if nothing else writes anything else in that
tree between the first command, tand the "tree" command.

I don’t think you can achieve what you want if the file keep generating. Ansible is not real time monitor/scanning. The most recently at the point of time when you trigger only.

Thanks and Best Regards,

Thanh.