Search code examples
macosbashls

How to list a directory with numbers so the user can select one in bash?


Okay so I'm basically trying to let the user decide which drive they would like to use to install software to. I'd like a question posted simular to "which drive would you like to install to?" and then it lists the drives numbered so that the user can easily select one of the drives. Is there a way to number ls results and then let the user select one. I was thinking about using the case command or maybe an echo and a read, But I just can't get this to work quite right. Also I should add this is in bash on a mac. Thank you so much.


Solution

  • Use select:

    PS3='which drive would you like to install to? '
    select dir in */ quit
    do
        if [[ $dir == quit ]]
        then
            break
        fi
        echo "$dir"    # or do other stuff
    done
    

    You can use a case statement inside the select block if that suits your needs.

    Also, see dialog and whiptail. Unfortunately, neither seem to come with OS X.