0
0
Bash Scriptingscripting~5 mins

grep in scripts in Bash Scripting

Choose your learning style9 modes available
Introduction
grep helps you find specific words or patterns in text files or command outputs quickly.
You want to find if a word exists in a log file.
You need to filter lines containing a certain phrase from a list.
You want to check if a service is running by searching process names.
You want to count how many times a word appears in a file.
You want to extract lines matching a pattern from command output.
Syntax
Bash Scripting
grep [options] pattern [file...]
pattern is the word or text you want to find.
If no file is given, grep reads from the keyboard or another command's output.
Examples
Finds lines containing the word 'error' in logfile.txt.
Bash Scripting
grep "error" logfile.txt
Shows running processes with 'ssh' in their details.
Bash Scripting
ps aux | grep "ssh"
Searches for 'warning' ignoring uppercase or lowercase letters.
Bash Scripting
grep -i "warning" logfile.txt
Counts how many lines contain the word 'fail' in logfile.txt.
Bash Scripting
grep -c "fail" logfile.txt
Sample Program
This script checks if any running process has 'bash' in its name and prints a message.
Bash Scripting
#!/bin/bash
# Check if 'bash' is running
if ps aux | grep -q "bash"; then
  echo "bash is running"
else
  echo "bash is not running"
fi
OutputSuccess
Important Notes
Use quotes around the pattern if it contains spaces or special characters.
The option -q makes grep quiet; it returns success or failure without printing lines.
grep is case-sensitive by default; use -i to ignore case.
Summary
grep helps find text patterns in files or outputs.
You can use it to filter, count, or check for text.
Options like -i and -c change how grep works.