0

I am trying to list all the directory latest modified folder first using select, but I am stuck.

Let's say I have:

Folder1
ThisIsAnotherDir
Directory
New Directory
This IS not_Same Directory

When I run following command:

ls -t -d */ 

I get the desired output.

But when I use select:

options=$(ls -t -d */)
select d in $options; do test -n "$d" && break; echo ">>> Wrong Folder Selection!!! Try Again"; done

It lists the folder modified first, but, if I modified New Directory last and run this, it outputs:

1)New 
2)Directory
3)Folder1
4)ThisIsAnotherDir
5)Directory
6)This 
7)IS 
8)not_Same 
9)Directory

I also tried:

select d in "$options[0]"; do test -n "$d" && break; echo ">>> Wrong Folder Selection!!! Try Again"; done

It fails also.

I hope this make sense. Thank you

kbulgrien
  • 780
  • 6
  • 21
KpDean
  • 3
  • 2
  • 2
    see https://unix.stackexchange.com/q/378282/330217 and corresponding answers. Try `select d in */` – Bodo Sep 01 '20 at 08:12
  • 2
    Does this answer your question? [bash: whitespace-safe procedural use of find into select](https://unix.stackexchange.com/questions/378282/bash-whitespace-safe-procedural-use-of-find-into-select) – andcoz Sep 01 '20 at 08:19
  • @Bodo select d in */ only gives me folders it does not order in with last modify folder 1st. – KpDean Sep 01 '20 at 08:57
  • @andcoz I had a look at that when i use it here select d in "$options[0]" output is only . nothing else. – KpDean Sep 01 '20 at 09:03
  • Add `echo "$options[@]"` just before the select line. This should help you to understand what it is happening. In any case, `"$options[0]"` is only the first element of the array, I suppose you should use `@` and not `0`. – andcoz Sep 01 '20 at 09:26
  • @andcoz it gives me same output regardless of what I use @ or 0. Only 1st folder is assign a number rest are doesn't have any assign number. i.e. 1)Folder1 Folder2 Folder3 ... – KpDean Sep 01 '20 at 09:40
  • See also [Why *not* parse `ls` (and what to do instead)?](https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead) – pLumo Sep 01 '20 at 10:44

1 Answers1

0

Combining the answer in https://unix.stackexchange.com/a/378304/330217 with your ls -t command you can try

IFS= mapfile -t files < <(ls -t -d */)

select d in "${files[@]}"
do
    test -n "$d" && break
    echo ">>> Wrong Folder Selection!!! Try Again"
done

Note that this solution doesn't work if you have a directory with a newline (or maybe other special characters) in its name.

Bodo
  • 5,979
  • 16
  • 27