【问题标题】:Print error message if no results have been found using find如果使用 find 未找到任何结果,则打印错误消息
【发布时间】:2014-09-09 13:06:17
【问题描述】:

我正在尝试编写一个 bash 脚本来打印路径 $1 中所有在 $2 之后修改的文件。这是我的脚本:

find ./$1 -mtime -$2 -type f | xargs du -h | sort

现在,如果脚本没有返回任何结果,我希望它打印一条错误消息,例如“未找到此类文件”。当且仅当没有找到和打印文件名时,我如何打印消息?

提前致谢。

【问题讨论】:

  • 您可以存储结果并检查变量是否有内容;如果不是,则打印此错误;如果是,打印输出:[ -z "$result" ] && echo "nothing found" || echo "$result"

标签: bash shell unix xargs


【解决方案1】:

你可以使用:

#!/bin/bash

# create a temp file
tmp=$(mktemp)

# run find and redirect output to temp file
find ./"$1" -mtime -"$2" -type f > "$tmp"

# check if temp file is not empty 
if [[ -s "$tmp" ]]; then
    cat "$tmp"
else
    echo "No such files found"
fi

# delete temp file
rm "$tmp"

【讨论】:

  • 我们可以将整个输出存储在一个局部变量中,并检查打印实际结果与打印No such files found
  • 存储在文件中不是更好吗?
  • 是的,我同意使用临时文件会比局部变量更好。
猜你喜欢
  • 2021-01-16
  • 2012-05-31
  • 2014-09-21
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2023-03-29
  • 2013-12-25
  • 1970-01-01
相关资源
最近更新 更多