You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何存储grep -q命令执行结果,在含其他代码的条件语句中满足条件时调用

解决方案

你完全可以只执行一次grep命令,将结果存储到变量或临时文件中,无需重复执行两次搜索,适合大规模落地的性能要求。

方案1:结果存入变量(适合搜索结果量级不大的场景)

# 仅执行一次搜索,同时捕获带行号的匹配结果
grep_result=$(grep -Ern 'break;|continue' *)

if [[ -n ${grep_result} ]]; then
    echo -e "\nfound breaks and/or continues:"
    echo "${grep_result}"
# 不需要无匹配提示的话可以删除整个else分支,满足未匹配无输出的要求
else
    # echo "no breaks or continues found."
    :
fi

方案2:结果存入临时文件(适合搜索结果量大、避免占用过多内存的大规模扫描场景)

# 创建临时文件,脚本退出时自动清理
temp_file=$(mktemp)
trap 'rm -f "${temp_file}"' EXIT

# 仅执行一次搜索,结果写入临时文件
grep -Ern 'break;|continue' * > "${temp_file}"

# 判断临时文件非空即存在匹配
if [[ -s ${temp_file} ]]; then
    echo -e "\nfound breaks and/or continues:"
    cat "${temp_file}"
fi

补充说明

如果需要额外判断grep的执行状态(比如区分「无匹配」和「grep执行出错」),可以在grep执行后立刻捕获退出码:

grep -Ern 'break;|continue' * > "${temp_file}"
grep_exit_code=$?
# 退出码说明:0=匹配到内容,1=无匹配,≥2=执行出错

内容的提问来源于stack exchange,提问作者list 'r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:54:05