Reputation: 25
Following up on someone else's question titled "Until user input equals something do". My script asks user for a filename. The script must search for the file. If the file does not exist in the directory, user must again be prompted for filename until they enter file that exists (must persist until true, without exiting program). Would it look something like?:
printf "Enter filename: "
read ifile
while [[ ! -e "$ifile" ]]
do
printf "File $ifile not found! "
done
When a file that does not exist is entered, I get a "runaway" loop until I have to cancel (CNTL + C). Example: If file filesa exists, but user "fat-fingers" it as filessa
Enter filename: filessa File filessa not found! File filessa not found! File filessa not found! File filessa not found! File filessa not found! File filessa not found! ...........on and on and on.
Any help is greatly appreciated!
Upvotes: 0
Views: 138
Reputation: 531315
There is an until
loop in bash
:
until [[ -e $ifile ]]; do
[[ -z $ifile ]] || printf "File $ifile not found!\n"
read -p "Enter filename: " ifile
done
Actually, until
is part of the POSIX standard as well, although a POSIX-compliant example would be less concise:
until [ -e "$ifile" ]; do
[ -z "$ifile" ] || printf "File $ifile not found!\n"
printf "Enter filename: "
read ifile
done
Upvotes: 1
Reputation: 37288
Try this
printf "Enter filename: "
read ifile
while [[ ! -e "$ifile" ]]
do
printf "File $ifile not found! \n"
printf "Enter filename: "
read ifile
done
If the user has entered the wrong filename, then you have to ask them to try again ;-).
Also, if the user doesn't enter anything, that will produce a different error. I would write the more extended check as
printf "Enter filename: "
read ifile
while [[ ! -e "${ifile:-XXXXno_user_inputXXXX}" ]]
do
printf "File ${ifile:-XXXXno_user_inputXXXX} not found! \n"
printf "Enter filename: "
read ifile
done
The var syntax ${var:-defaultValue}
can be read as "if the variable $var
is empty, then print the value after the :-
as a replacement value.
A pedantic objection to XXXXno_user_inputXXXX
is that it's possible that there might be a file in your directory already named XXXX_no_user_inputXXXX
, so you'll have to decide if that is a big risk for your project.
IHTH
Upvotes: 1