List files and show them in a menu with bash

后端 未结 2 1121
日久生厌
日久生厌 2021-01-01 19:38

I am trying to use the files in a directory as options in a bash script. The user should be able to select one and then pass the name of the selected file into a variable. S

相关标签:
2条回答
  • 2021-01-01 20:15

    I do not think case is suitable here:

    #!/bin/bash
    prompt="Please select a file:"
    options=( $(find -maxdepth 1 -print0 | xargs -0) )
    
    PS3="$prompt "
    select opt in "${options[@]}" "Quit" ; do 
        if (( REPLY == 1 + ${#options[@]} )) ; then
            exit
    
        elif (( REPLY > 0 && REPLY <= ${#options[@]} )) ; then
            echo  "You picked $opt which is file $REPLY"
            break
    
        else
            echo "Invalid option. Try another one."
        fi
    done    
    
    ls -ld $opt
    
    0 讨论(0)
  • 2021-01-01 20:27

    Don't miss percol, fzy, smenu and friends. They'll happily take from stdin, present a user-friendly select menu with interactive filter, then pipe selected lines out again.

    0 讨论(0)
提交回复
热议问题