0

I am listing files from a folder and taking an input from the user to select one of the files.

files=$(ls ~/VideoExtract/*.avi) i=1 for j in $files do echo "$i.$j" file[i]=$j i=$(( i + 1 )) done echo "" echo "" read -p "Enter the serial number from the above list : " input clear 

Suppose if I have 3 files, the above code lists all three files listed with serial numbers 1,2,3. I want to validate if the user provides the correct input and not break the code till receiving a correct input. To do this, I have used a while loop after the above code

while [[ "$input" =~ ["$i"] ]] do echo "Please provide a serial number from the list given below." files=$(ls ~/VideoExtract/*.avi) i=1 for j in $files do echo "$i.$j" file[i]=$j i=$(( i + 1 )) done read -p "Enter the serial number from the above list : " input done 

This does returns the list of files again. The problem is, if I have 3 files, and if I type 4, the loop continues to work, but if I provide 5 instead, the loop breaks and moves on to the next line of the code. I am not sure if the problem is in line

while [[ "$input" =~ ["$i"] ]] 

or

i=$(( i + 1 )) 

Instead of =~ I have tried with != and ! $input == $i and similar other combinations, such as with and without [] for $i. Nothing seem to work.

How do I run the while loop till the time the user provides a valid input that is within the range of $i.

    1 Answer 1

    1

    (On a mobile so a somewhat shorter than I'd prefer)

    =~ is a Regular Expression match. You don't want this here. Use -lt (less than) or -le (less than or equal) instead.

    There are also a number of other problems with your code

    • don't use ls to list a set of files, just use the set of files directly files=(~/VideoExtract/*.avi)
    • quote your variables when you use them file["$i"]="$j"
    • let the shell control the expansion of $files when you iterate over it for j in "${files[@]}"
    • not strictly necessary, but indenting your code blocks will make the code far far easier to read
    1
    • thank you....and I will include your other suggestions as well.
      – Apricot
      CommentedDec 6, 2017 at 7:06

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.