bhylu.com

Advertisements

Bash grep

Search for a literal field while distinguishing no match from an error.

How it works

grep selects matching text lines. Its regular-expression mode and fixed-string mode answer different questions; use -F when the pattern is data rather than a regex. A status of zero means a match, one means no match, and a larger status indicates an error. An analytical script should not report all nonzero results as the same failure.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

The complete source creates a fresh private temporary workspace and checks its physical path before cleanup. All file fixtures belong to that workspace; do not remove the guards or point it at existing documents.

Download complete source

Example

grep.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C

# Own a new directory; verify physical paths before cleanup.
parent=$(cd -- "${TMPDIR:-/tmp}" && pwd -P) || exit 1
work=$(mktemp -d "$parent/bhylu-bash.XXXXXX") || exit 1
work=$(cd -- "$work" && pwd -P) || exit 1
case "$work" in "$parent"/bhylu-bash.??????) ;; *) exit 1 ;; esac
cleanup() {
    cd -- "$parent" || return 1
    [[ -d $work && ! -L $work ]] || return 1
    [[ $(cd -- "$work" && pwd -P) == "$work" ]] || return 1
    case "$work" in "$parent"/bhylu-bash.??????) rm -r -- "$work" ;; *) return 1 ;; esac
}
trap cleanup EXIT
cd -- "$work" || exit 1

printf "north,ready\nsouth,draft\n" > jobs.txt
grep -F -- "north,ready" jobs.txt
if grep -F -- "west,ready" jobs.txt >/dev/null; then
    exit 1
else
    status=$?
    [[ $status -eq 1 ]] || exit "$status"
fi

Focus on the lesson commands

This excerpt omits temporary-workspace setup and cleanup. Use the complete source above to run the example.

Command excerpt

printf "north,ready\nsouth,draft\n" > jobs.txt
grep -F -- "north,ready" jobs.txt
if grep -F -- "west,ready" jobs.txt >/dev/null; then
    exit 1
else
    status=$?
    [[ $status -eq 1 ]] || exit "$status"
fi

Expected result

north,ready

The fixed pattern is passed after -- so a leading dash would not become an option. The missing west row produces the expected no-match status, which is checked explicitly. The source has a deliberately simple line format; grep does not parse quoted CSV or understand a field’s semantic type.

Primary technical reference: Bash documentation.