How To Use select command in bashscript

How To Use select command in bashscript

Imagine that you are creating a script that lets user selects one file out of many files in directory. well this can be achived in different ways

The Hard Way

#!/bin/bash
content=$(dir);
str="`echo $content`";
read -r -a list <<<${str};
read -p "Enter file name you want : " filename;
for i in ${list[@]}; do
# now lets check 
    if [[  $filename == $i ]]; then
        # your script goes here
        echo "found it"
    fi

done
# Output
Enter file name you want : test0.txt
found it
# Output
Enter file name you want : test0

Using Select Command

select assigns a number to a each file and tell us to select one with a specific number Our reply is stored in variable REPLY.

#!/bin/bash
select name in *;
do
    echo "you selected : $REPLY";
    echo "file name is : $name";
    break;
done
# Output 
1) test0.txt
2) test1.txt
3) test2.txt
#? 1
you selected : 1
file name is : test0.txt