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

如何在Bash脚本中使用错误校验检查文件条目——为物种查询脚本添加未找到提示

How to Add "Not Found" Error Checking to Your Bash Species Search Script

Got it, let's tweak your existing script to show a "未找到" message when the user's input doesn't match any entry in speciesDetails.txt. The key here is using Bash's exit code checking—every command in Bash returns an exit code (0 for success, non-zero for failure), and grep specifically returns 1 when it finds no matches.

Option 1: Capture Results and Exit Code (Explicit Approach)

This method stores the search results first, then checks if grep found anything:

#!/bin/bash
echo 'Please enter the name of the species you are looking for: '
read speciesName

# Capture the grep results and save its exit code
search_results=$(grep "$speciesName" speciesDetails.txt)
grep_status=$?

# Check if grep succeeded (exit code 0 = matches found)
if [ $grep_status -eq 0 ]; then
    echo "$search_results"
else
    echo "未找到"
fi

echo
echo 'Would you like to search for another species? Press y to search or n to go back to the main menu: '
read answer
case $answer in
[yY] | [yY][eE][sS] ) ./searchSpecies.sh;;
[nN] | [nN][oO] ) ./speciesMenu.sh;;
*) echo exit;;
esac

What's changed:

  • $(grep "$speciesName" speciesDetails.txt) saves all matching lines to the search_results variable.
  • $? is a special Bash variable that holds the exit code of the last command—we store it in grep_status to check later.
  • The if statement checks if grep returned 0 (success). If yes, we print the results; if not, we show the "未找到" error.

Option 2: Quiet Grep (Simpler Approach)

You can use grep's -q (quiet) flag to skip output and only check the exit code, then run grep again to print results if needed:

#!/bin/bash
echo 'Please enter the name of the species you are looking for: '
read speciesName

# Use grep -q to check for matches without outputting anything
if grep -q "$speciesName" speciesDetails.txt; then
    # If matches exist, print them
    grep "$speciesName" speciesDetails.txt
else
    echo "未找到"
fi

echo
echo 'Would you like to search for another species? Press y to search or n to go back to the main menu: '
read answer
case $answer in
[yY] | [yY][eE][sS] ) ./searchSpecies.sh;;
[nN] | [nN][oO] ) ./speciesMenu.sh;;
*) echo exit;;
esac

Why this works:

  • The -q flag makes grep run silently—no output, just an exit code. If it finds matches, it returns 0; if not, 1.
  • The if statement runs grep -q directly: if the command succeeds (exit code 0), we run grep again to show the results. If not, we output the error message.

Both approaches will reliably trigger the "未找到" message when no matching species exists in the file.

内容的提问来源于stack exchange,提问作者KokaDoodles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:27:45