while loop for checking a file name exists or not

2019-09-13 16:44发布

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.

2条回答
ら.Afraid
2楼-- · 2019-09-13 17:03

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.

查看更多
甜甜的少女心
3楼-- · 2019-09-13 17:09

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}"
查看更多
登录 后发表回答