Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List files and show them in a menu with bash

Tags:

bash

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. So far I can get the list of files, but after a few hours trying I can't figure out how to show them as options.

#!/bin/bash
prompt="Please select a file:"
options=( $(find -maxdepth 1 -print0 | xargs -0) )

PS3="$prompt "
select opt in "${options[@]}" "Quit"; do 

    case "$REPLY" in
    for i in "${options[@]}"
    do
    $i' ) echo "You picked $opt which is file $REPLY";;'
    done    
    $(( ${#options[@]}+1 )) ) echo "Goodbye!"; break;;
    *) echo "Invalid option. Try another one.";continue;;

    esac

done

Any help is much appreciated. Thanks!

like image 376
castaway Avatar asked Apr 04 '13 09:04

castaway


People also ask

How do I see files in a bash script?

In order to check if a file exists in Bash, you have to use the “-f” option (for file) and specify the file that you want to check. For example, let's say that you want to check if the file “/etc/passwd” exists on your filesystem or not. In a script, you would write the following if statement.

How do I get a list of files in a directory in bash?

Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

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
like image 162
choroba Avatar answered Oct 21 '22 09:10

choroba