简体   繁体   English

Bash:If语句嵌套在for循环中

[英]Bash: If statement nested in for loop

I am writing a simple script to check if an entered directory path exists. 我正在编写一个简单的脚本来检查是否存在输入的目录路径。 This is what I have 这就是我所拥有的

echo "Please specify complete directory path"
read file_path

for file in $file_path; do
    if [[ -d "$file" ]]; then
        echo "$file is a directory"
        break
    else
        echo "$file is not a directory, please try again."
fi
done

What I need is if it is not a directory to go back and ask for the file path again. 我需要的是,如果它不是一个目录,请再次返回文件路径。

Thanks. 谢谢。

How about this? 这个怎么样?

echo "Please specify complete directory path"

while read file; do
    if [[ -d "$file" ]]; then
        echo "$file is a directory"
        break
    fi
    echo "$file is not a directory, please try again."
done

No need to split the path into its parts, testing the entire path with -d will tell you whether or not it is a directory. 无需将路径分成多个部分,使用-d测试整个路径将告诉您它是否是目录。 You need to put the entire test into a while loop until the user gets it right: 您需要将整个测试放入while循环中,直到用户正确为止:

#/bin/sh
set -e
file_path=''
while [ ! -d "$file_path" ]
do
    echo "Please specify complete directory path"
    read file_path   
    if [ ! -d "$file_path" ]
    then
        echo "$file_path is not a directory, please try again."
    fi
done

I can use it like this 我可以这样使用

$ sh /tmp/test.sh 
Please specify complete directory path
foobar
foobar is not a directory, please try again.
Please specify complete directory path
/var/www

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM