如何在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 thesearch_resultsvariable.$?is a special Bash variable that holds the exit code of the last command—we store it ingrep_statusto check later.- The
ifstatement checks ifgrepreturned 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
-qflag makesgreprun silently—no output, just an exit code. If it finds matches, it returns 0; if not, 1. - The
ifstatement runsgrep -qdirectly: if the command succeeds (exit code 0), we rungrepagain 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
相关产品推荐
相关产品推荐

