Bash脚本 - 如何在找到文件之前保持循环'find'命令?

时间:2014-07-08 01:52:19

标签: linux bash shell unix find

我对linux脚本编程非常陌生。我正在尝试建立一个简单的循环:

  1. 询问用户的文件名
  2. 在特定目录中搜​​索文件
  3. 如果未找到任何文件,请要求用户重新输入文件名
  4. 如果找到文件,请转到脚本的下一步
  5. 这是我到目前为止所做的,但它根本没有循环(即没有找到文件时,它不会要求用户重新输入文件名。)

    #!/bin/bash
    read -p "Enter file name: " file
    find /directory/ -name "$file" -print
    while [ "$?" -ne 0 ]; do
           read -p "File not found. Please re-enter file name: " file
           find /directory/ -name "$file" -print
    done
    echo "rest of script etc" 
    

    任何帮助表示赞赏! :)

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用globstar(bash 4提供)

#!/bin/bash
shopt -s globstar
while true; do
    read -p "Enter file name: " file
    for f in /directory/**/"$file"; do
        echo "$f"
        break 2 # escape both loops
    done
    echo "'$file' not found, please try again."
done
echo "rest of script etc"

它也可能与find有关,但有点烦人,因为你不能使用标准的UNIX退出状态:

#!/bin/bash
read -p "Enter file name: " file
found=$(find /directory/ -name "$file" -print -quit)
while [[ -z $found ]]; do
    read -p "File not found. Please re-enter file name: " file
    found=$(find /directory/ -name "$file" -print -quit)
done
echo "$found"
echo "rest of script etc"

通常我不建议解析find的输出,但在这种情况下,我们只关心是否有任何输出。

答案 1 :(得分:-1)

最简单,最便携的方式可能是:

# Loop until user inputted a valid file name
while true ; do
    # Read input (the POSIX compatible way)
    echo -n "Enter file name: "
    read file

    # Use find to check if the file exists
    [ $(find /etc -type f -name "$file" 2>/dev/null | wc -l ) != "0" ]  && break

    # go to next loop if the file does not exist
done

echo "Ok, go on here"