Bird
Raised Fist0
Bash Scriptingscripting~10 mins

grep in scripts in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - grep in scripts
Start script
↓
Run grep command
↓
Check grep output
↓
End script
The script runs grep to search text, then acts based on whether grep finds a match or not.
Execution Sample
Bash Scripting
if grep -q "hello" file.txt; then
  echo "Found hello"
else
  echo "No hello found"
fi
This script checks if the word 'hello' is in file.txt and prints a message accordingly.
Execution Table
StepCommandGrep ResultConditionActionOutput
1grep -q "hello" file.txtMatch foundTrueEnter then branchecho "Found hello"
2echo "Found hello"N/AN/APrint messageFound hello
3EndN/AN/AScript ends
💡 grep found 'hello' in file.txt, so condition is true and script prints 'Found hello'
Variable Tracker
VariableStartAfter grepAfter echoFinal
grep exit statusN/A0 (match)N/A0
output messageN/AN/A"Found hello""Found hello"
Key Moments - 3 Insights
Why does the script use 'grep -q' instead of just 'grep'?
'grep -q' runs quietly without printing matches, so the script only checks if a match exists (see execution_table step 1). This avoids cluttering output.
What does the exit status 0 from grep mean?
Exit status 0 means grep found a match (see variable_tracker 'grep exit status' after grep). Non-zero means no match.
Why is the echo command inside the then branch?
Because the condition is true only if grep finds a match, so echo prints 'Found hello' only then (see execution_table step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the grep exit status after step 1?
A1 (no match)
B0 (match found)
C2 (error)
DN/A
💡 Hint
Check variable_tracker row 'grep exit status' after grep command
At which step does the script print the output message?
AStep 2
BStep 3
CStep 1
DNo output printed
💡 Hint
Look at execution_table 'Action' and 'Output' columns
If the file.txt did not contain 'hello', what would happen?
AScript prints 'Found hello'
BScript crashes
CScript prints 'No hello found'
DScript prints nothing
💡 Hint
Think about grep exit status when no match and how if-else branches work
Concept Snapshot
grep in scripts:
Use 'grep -q pattern file' to quietly check for text.
Check grep exit status: 0 means match, non-zero means no match.
Use if-then-else to run commands based on grep result.
Example:
if grep -q "text" file; then echo "Found"; else echo "Not found"; fi
Full Transcript
This visual execution shows how grep is used in a bash script to check if a file contains a word. The script runs 'grep -q' to search quietly. If grep finds the word, its exit status is 0, so the script prints 'Found hello'. If not found, it prints 'No hello found'. The execution table traces each step, showing the grep command, its result, the condition check, and the output. The variable tracker shows how grep's exit status changes and how the output message is set. Key moments clarify why 'grep -q' is used, what exit status means, and why echo is inside the then branch. The quiz tests understanding of grep exit status, output timing, and behavior when no match is found. The snapshot summarizes the pattern for using grep in scripts with if-else to handle matches.

Practice

(1/5)
1. What does the grep command do in a bash script?
easy
A. Searches for lines matching a pattern in files or input
B. Deletes files matching a pattern
C. Creates new files with matching names
D. Changes file permissions based on a pattern

Solution

  1. Step 1: Understand grep's purpose

    The grep command is used to search text for lines that match a given pattern.
  2. Step 2: Compare options

    Options B, C, and D describe actions unrelated to searching text, so they are incorrect.
  3. Final Answer:

    Searches for lines matching a pattern in files or input -> Option A
  4. Quick Check:

    grep = search text lines [OK]
Hint: grep finds text patterns in files or input quickly [OK]
Common Mistakes:
  • Thinking grep deletes or modifies files
  • Confusing grep with commands like rm or chmod
  • Assuming grep creates files
2. Which of the following is the correct syntax to search for the word "error" in a file named log.txt using grep?
easy
A. grep -f error log.txt
B. grep error log.txt
C. grep log.txt error
D. grep -c log.txt error

Solution

  1. Step 1: Identify grep syntax

    The correct syntax is grep [pattern] [file]. So, searching for "error" in "log.txt" is grep error log.txt.
  2. Step 2: Check other options

    grep -f error log.txt uses -f which expects a file of patterns, not a pattern string. Options C and D have arguments reversed or wrong flags.
  3. Final Answer:

    grep error log.txt -> Option B
  4. Quick Check:

    grep pattern file = correct syntax [OK]
Hint: Remember: grep pattern filename [OK]
Common Mistakes:
  • Swapping pattern and filename order
  • Using -f flag incorrectly
  • Confusing -c flag usage
3. What will be the output of this script snippet?
echo -e "apple\nbanana\nApple" | grep -i apple
medium
A. apple
B. No output
C. apple\nApple
D. Apple

Solution

  1. Step 1: Understand the input

    The input lines are "apple", "banana", and "Apple".
  2. Step 2: Apply grep with -i option

    The -i option makes grep case-insensitive, so it matches both "apple" and "Apple" but not "banana".
  3. Final Answer:

    apple\nApple -> Option C
  4. Quick Check:

    grep -i matches case-insensitive lines [OK]
Hint: Use -i to ignore case when searching [OK]
Common Mistakes:
  • Ignoring case sensitivity of grep
  • Expecting only lowercase matches
  • Assuming grep outputs only one match
4. Identify the error in this script snippet:
if grep "error" logfile.txt
then
  echo "Error found"
fi
medium
A. Missing semicolon or newline before then
B. grep command syntax is wrong
C. echo command should be outside if block
D. fi is missing

Solution

  1. Step 1: Check if statement syntax

    In bash, the if condition must end with a semicolon or newline before then. Here, then is on a new line and the previous line ends properly, so syntax is correct.
  2. Step 2: Confirm other parts

    grep syntax is correct, echo is correctly inside if, and fi is present.
  3. Final Answer:

    No error in the script snippet -> Option A
  4. Quick Check:

    if condition syntax is correct as given [OK]
Hint: Put ; or newline before then in if statements [OK]
Common Mistakes:
  • Writing if and then on same line without semicolon
  • Misplacing fi or echo commands
  • Confusing grep syntax with if syntax
5. You want to count how many lines in data.txt contain the word "success" ignoring case, and store the number in a variable count. Which script snippet correctly does this?
hard
A. count=$(grep -i success -c data.txt)
B. count=$(grep -c success -i data.txt)
C. count=$(grep success -i -c data.txt)
D. count=$(grep -ci success data.txt)

Solution

  1. Step 1: Understand grep options

    The -c option counts matching lines, and -i ignores case. Both can be combined as -ci.
  2. Step 2: Check option order and syntax

    Options A, B, and D have options separated or misplaced. count=$(grep -ci success data.txt) correctly combines -c and -i before the pattern and filename.
  3. Final Answer:

    count=$(grep -ci success data.txt) -> Option D
  4. Quick Check:

    Use combined options -ci for count and ignore case [OK]
Hint: Combine options like -ci for count and ignore case [OK]
Common Mistakes:
  • Separating options incorrectly
  • Placing options after filename
  • Not combining -c and -i properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard