PS3 select when wrong input given

Hi All

I am using the below code to chose a file to view :

PS3="Select file to view : "
select FILE in `ls`  QUIT
do
   if [ -e $FILE ] ; then
     clear
     cat  $FILE
  else
  break
  fi
  REPLY=''
done

Everything works fine as long as I am giving the correct choice .

But when i give a wrong option it hangs .
How to include a check so that if a wrong option is entered , throw a message saying to enter a valid choice.

PS3="Select file to view : "
select FILE in `ls`  QUIT
do
   if [ -z "$FILE" ]
   then
    echo INVALID INPUT
   else
    if [ -e "$FILE" ]
    then
     clear
     cat  "$FILE"
    else
     break
    fi
   fi
done
1 Like

Thanks for the above solution .
Another tip I want for removing the chosen option to not appear in the options.
Say i chose 1) filname1 . I dont want it to appear again.

I have tried like below (HP UNIX) but cannot get it to work:

PS3="Enter corresponding number and hit enter:"
select DIR in `cat mylist`  QUIT
do
if [ -z "$DIR" ]
   then
   echo "INVALID INPUT"
else
if [ -d "$mysource/$DIR" ]; then
echo "Copying $mysource/$DIR ................................"
             cp -rp $mysource/$DIR $mydest/
 
                  mv -f mylist mylist1
                  perl -ne "print unless /\b$DIR\b/" mylist1 > mylist
               
else
     break
  fi
  fi
  REPLY=''
done

I don't think this is possible with select .
With a construct such as:

select DIR in `cat mylist`  QUIT
do
.
.
.
done

changing the file mylist inside the loop will not work at all. The shell has already done command substitution for cat mylist and substituted the output of that command in place of `cat mylist` , before running the other commands in the loop. So, the argument list to select is a static one.

1 Like

Thanks a lot Batman. :slight_smile:
I will look for some workaround.