while loop for checking a file name exists or not

2019-09-13 16:37发布

问题:

filename=""
while [[ $filename = "" ]];do
    echo "Enter the file name"
    read filename
    if [[ -f $filename ]];then
        echo "$filename exists"
    else
        echo "File name doesn't exists, so re-enter"
    fi
done

with this style of loop, the loop exists when the file name is not present. But i want the loop to continue until the user input the file name. Please suggest what additional command i should include in the above script.

回答1:

Use break to get out of the loop

while true ; do
   echo "Enter the file name"
   read filename
   if [ -f "${filename}" ]; then
       echo "${filename} exists"
       break
   else
       echo "File name doesn't exists, so re-enter"
   fi
done
echo "Thanks for ${filename}"

or shorter

while true ; do
   read -p "Enter the file name: " filename
   test -f "${filename}" && break
   echo "File name doesn't exists, so re-enter"
done
echo "Thanks for ${filename}"


回答2:

Quick and dirty way of doing it while utilizing the same code you have is simply adding your code inside an infinite loop.

while :
do
    filename=""
    while [[ $filename = "" ]];do
        echo "Enter the file name"
        read filename
        if [[ -f $filename ]];then
            echo "$filename exists"
        else
            echo "File name doesn't exists, so re-enter"
        fi
    done
done

Keep in mind that this will only look within the directory that the program is executed from unless a full path is given.