【问题标题】:Bash script - how to keep looping 'find' command until file/s are found?Bash 脚本 - 如何在找到文件之前一直循环“查找”命令?
【发布时间】:2014-07-08 01:52:18
【问题描述】:

我对 linux 脚本非常陌生,我正在尝试设置一个简单的循环,它将:

  1. 询问用户文件名
  2. 在特定目录中搜​​索文件
  3. 如果未找到文件,请用户重新输入文件名
  4. 如果找到文件,请继续执行脚本的下一步

这是我目前所拥有的,但它根本没有循环(即当没有找到文件时,它不会要求用户重新输入文件名。)

#!/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" 

感谢任何帮助! :)

【问题讨论】:

  • find 在错误时返回非 0,如果没有找到文件则不会。请参阅this 以获得简单的修复。此外,请考虑将-quit 添加到您的find 命令以在找到一个匹配项后停止遍历。

标签: linux bash shell unix find


【解决方案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的输出,但在这种情况下,我们只关心是否有任何输出。

【讨论】:

  • 您应该明确启用 globstar,因为它不是默认设置。
【解决方案2】:

最简单和最便携的方法可能是这样的:

# 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"

【讨论】:

  • 这与find /directory -name "$file" 的作用不同。
  • 感谢 hek2mgl 的建议,但正如@kojiro 所说,这并没有做同样的事情。我需要使用 find 命令,只要命令不返回任何内容,就可以循环。
  • 一个提示就足够了,很难从这个问题中得到答案。尤其是在专注于需求的文本表示时。感谢@kojiro 的反对票。干得好!
  • @user3792362 是否要递归搜索目录?意思是,也在它的子目录中?
  • @hek2mgl 是的,我想搜索 /directory/ 下的每个位置
猜你喜欢
  • 2017-07-08
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
相关资源
最近更新 更多