grep1-1 Exercise 3: A Script That Reads grep's Exit Status =========================================================== cat > check.sh <<'EOF' #!/bin/bash # usage: check.sh WORD FILE grep -q -- "$1" "$2" case $? in 0) echo "found" ;; 1) echo "missing" ;; *) echo "error: could not search $2" >&2; exit 2 ;; esac EOF cat > server.log <<'EOF' 2026-10-08 09:15:48 ERROR database connection lost 2026-10-08 09:30:00 INFO backup finished EOF printf -- '-v is the invert flag\n' > notes.txt bash check.sh ERROR server.log; echo "exit status: $?" bash check.sh CRITICAL server.log; echo "exit status: $?" bash check.sh ERROR nosuchfile; echo "exit status: $?" bash check.sh -v notes.txt; echo "exit status: $?" Output: found exit status: 0 missing exit status: 0 grep: nosuchfile: No such file or directory error: could not search nosuchfile exit status: 2 found exit status: 0 WHY THIS WORKS AS AN ANSWER --------------------------- grep -q prints nothing; the script reads only the status in $?. 0 is 'found', 1 is 'missing' (which is a normal answer, not a failure), and anything else (in practice 2) is an error, reported on standard error with exit status 2 so that whoever called the script can tell the difference. The -- after -q means 'options end here', so a word like -v is searched for instead of being mistaken for the invert flag. Without it grep would take -v as the invert option, take notes.txt as the PATTERN, and read standard input instead of the file: in a terminal it would sit there waiting for you to type, and with empty input (I tried it) it quietly reports 'no match', a wrong answer with no error message. The quotes around "$1" and "$2" keep a word or file name with spaces in one piece. In the third test grep also prints its own 'No such file or directory' message before the script's one. Chapter 4 shows -s for hiding that.