READ Command – Technical Reference:
The read command is used to take input from the user or standard input and store it in a variable. It is fundamental for interactive shell scripts, allowing scripts to prompt users, read files, or handle input dynamically.
Basic Syntax
read [options] variable_name
Reads a line and stores it in the variable
If no variable is specified, input is stored in REPLY
Example:
read name
echo "Hello, $name"
Prompting the User
read -p "Enter your name: " name
echo "Hello, $name"
-p "prompt" → displays a prompt before reading input
Silent Input (Password)
read -s -p "Enter password: " password
echo
echo "Password accepted"
-s → input not displayed
Use echo to move to a new line after input
Timeout Option
read -t 5 -p "Enter your name within 5 seconds: " name
if [ -z "$name" ]; then
echo "Timeout!"
else
echo "Hello, $name"
fi
-t seconds → timeout in seconds
Reading Multiple Variables
read first_name last_name
echo "First: $first_name, Last: $last_name"
Input is split by whitespace
Extra words are stored in the last variable
read a b
# Input: 1 2 3 4 → a=1, b="2 3 4"
Reading Into an Array
read -a arr
# Input: 1 2 3 → arr[0]=1, arr[1]=2, arr[2]=3
-a → store input into an array
Specifying Input Field Separator
IFS="," read var1 var2
# Input: apple,banana → var1=apple, var2=banana
IFS → Internal Field Separator used to split input
Reading a Single Character
read -n 1 -p "Press any key: " key
echo
echo "You pressed $key"
-n N → read N characters without waiting for Enter
Reading Without Backslash Interpretation
read -r line
-r → prevents \ from being treated as escape characters
Checking Exit Status
if read -t 3 -p "Enter value: " val; then
echo "You entered $val"
else
echo "No input or timeout!"
fi
Returns 0 on success, non-zero on EOF or timeout
Reading From a File
while IFS= read -r line; do
echo "Line: $line"
done < file.txt
IFS= prevents trimming of spaces
-r prevents backslash escapes
Common Options
Option Description
-p Prompt message
-s Silent mode (password input)
-t Timeout in seconds
-n Read N characters
-r Raw input, no backslash interpretation
-a Read input into an array
-d Use a custom delimiter (default newline)
Examples
Basic input:
read name
echo "Hello, $name"
Prompt with silent input:
read -s -p "Password: " pwd
echo
echo "Password received"
Timeout input:
read -t 5 -p "Enter your age: " age
Multiple variables:
read fname lname
echo "First: $fname, Last: $lname"
Reading into an array:
read -a colors
echo "Colors: ${colors[0]}, ${colors[1]}"
Reading file line by line:
while IFS= read -r line; do
echo "$line"
done < file.txt
Single character input:
read -n 1 -p "Press Y to continue: " ans
echo
CAT Command – Technical Reference:
cat (concatenate) is a versatile command used to display file contents, combine files, create new files, and number lines. It works with stdin, stdout, and file redirection, making it essential for file inspection and quick text manipulation in shell scripts.
Basic Syntax
cat [options] [file1 file2 ...]
Reads files sequentially; if no files are provided, reads from stdin.
Multiple files are concatenated in the order specified.
Displaying File Contents
cat file.txt
Displays the entire contents of a file to the terminal.
Concatenating Multiple Files
cat file1.txt file2.txt
Outputs the contents of file1.txt followed by file2.txt.
Combine into a new file:
cat file1.txt file2.txt > combined.txt
Append to an existing file:
cat file1.txt >> combined.txt
Creating a New File
cat > newfile.txt
# Type content, press Ctrl+D to save
Ctrl+D signals EOF to end input.
Numbering Lines
Number all lines:
cat -n file.txt
Number only non-blank lines:
cat -b file.txt
Showing Non-Printing Characters
Option Description
-T Show tabs as ^I
-E Show $ at end of lines
-v Show non-printable characters
-A Show all non-printing characters (-vET)
Example:
cat -vET file.txt
Reading from Standard Input
cat
# Type text, press Ctrl+D to exit
echo "Hello World" | cat
# Output: Hello World
Appending to Files
cat >> file.txt
# Adds input to the end of file (Ctrl+D to finish)
Advanced Examples
Combine multiple files and number lines:
cat -n file1.txt file2.txt > combined.txt
View file with line endings:
cat -E file.txt
Pipe through other commands:
cat file.txt | grep "pattern"
cat file.txt | sort | uniq
Tips and Best Practices
Use cat for small files; for huge files, prefer less or more.
Avoid unnecessary cat with pipes (e.g., grep pattern file.txt instead of cat file.txt | grep pattern).
Combine options for advanced display: cat -bET file.txt.
Common Options
Option Description
-n Number all lines
-b Number only non-blank lines
-E Show $ at end of lines
-T Show tabs as ^I
-v Show non-printing characters
-A Show all non-printing characters (-vET)
> / >> Redirect output to file
FIND Command – Technical Reference:
find is a powerful command to search for files and directories in a directory hierarchy based on name, type, size, permissions, time, and other criteria. It is widely used in automation, scripting, and system administration.
Basic Syntax
find [path...] [options] [expression]
path → directories to search (default: .)
expression → conditions like name, type, size, permissions
options → control search behavior, e.g., -maxdepth, -mindepth
Searching by Name
find /path/to/dir -name "file.txt" # case-sensitive
find /path/to/dir -iname "file.txt" # case-insensitive
find /path/to/dir -name "*.txt" # wildcard support
Searching by Type
-type f # regular files
-type d # directories
-type l # symbolic links
Searching by Size
-size 10M # exactly 10 MB
-size +10M # larger than 10 MB
-size -10M # smaller than 10 MB
Suffixes: c=bytes, k=KB, M=MB, G=GB
Searching by Time
-mtime 0 # modified today
-mtime +7 # modified more than 7 days ago
-mtime -7 # modified within last 7 days
-atime # last accessed
-ctime # last metadata change
Searching by Permissions
-perm 644 # exact mode
-perm -u=x # executable by user
-perm /mode # any bit matches
Combining Conditions
AND (default):
find /dir -type f -name "*.txt" -size +1M
OR:
find /dir -type f -name "*.txt" -o -name "*.md"
NOT:
find /dir ! -name "*.txt"
Grouping:
find /dir \( -name "*.txt" -o -name "*.md" \) -size +1M
Executing Commands on Found Files
find /dir -name "*.log" -exec rm {} \;
find /dir -type f -exec chmod 644 {} \;
find /dir -type f -exec ls -l {} \;
{} → placeholder for found file
\; → ends command
+ → pass multiple files at once for efficiency
Limiting Depth
-maxdepth 1 # only current directory
-mindepth 2 # start search from depth 2
Finding Empty Files or Directories
-type f -empty # empty files
-type d -empty # empty directories
Deleting Files
find /dir -type f -name "*.tmp" -delete
Use with caution; -delete removes files immediately
Recently Accessed or Modified
-type f -mtime -1 # modified within 1 day
-type f -atime -7 # accessed within 7 days
Using find with xargs
find /dir -name "*.log" | xargs rm
find /dir -name "*.log" -print0 | xargs -0 rm # handles spaces safely
Common Options Quick Reference
Option Description
-name Search by file name (case-sensitive)
-iname Search by file name (case-insensitive)
-type f=file, d=directory, l=symlink
-size + greater, - less, c/k/M/G
-mtime Modification time (days)
-atime Access time
-ctime Metadata change time
-perm Match file permissions
-exec Execute command on found files
-delete Delete found files
-maxdepth N Limit search depth
-mindepth N Start search from depth N
! NOT operator
-o OR operator
\( \) Group expressions
GREP Command – Technical Reference:
grep (Global Regular Expression Print) is a powerful text search tool that searches for patterns, words, or regular expressions in files or input streams. It is widely used for filtering, pattern matching, and scripting pipelines.
Basic Syntax
grep [options] pattern [file...]
pattern → text or regex to search for
file → file(s) to search (if omitted, reads from stdin)
Examples:
grep "hello" file.txt
echo "hello world" | grep "hello"
Case-Insensitive Search
grep -i "hello" file.txt
-i → ignore case (Hello, HELLO, hello)
Searching for Whole Words
grep -w "word" file.txt
-w → match only whole words, not substrings
Displaying Line Numbers
grep -n "pattern" file.txt
-n → show line number of matching lines
Counting Matches
grep -c "pattern" file.txt
-c → only shows the number of matching lines
Inverting Match
grep -v "pattern" file.txt
-v → prints lines that do NOT match the pattern
Recursive Search
grep -r "pattern" /path/to/dir
grep -r --include="*.txt" "pattern" /dir
-r / -R → search recursively
--include → limit search to specific files
Using Regular Expressions
Type Example Option
Basic regex grep "he..o" file.txt -
Extended regex `grep -E "cat dog" file.txt`
Fixed string grep -F "a+b*c" file.txt -F
Showing Context Around Matches
grep -C 2 "pattern" file.txt # 2 lines before & after
grep -B 3 "pattern" file.txt # 3 lines before
grep -A 4 "pattern" file.txt # 4 lines after
-C → context, -B → before, -A → after
Display Only Matching Part
grep -o "pattern" file.txt
-o → prints only matched text, not whole line
Quiet Mode
grep -q "pattern" file.txt
if [ $? -eq 0 ]; then echo "Found!"; else echo "Not found!"; fi
-q → suppress output; only sets exit code
Multiple Patterns
grep -e "pattern1" -e "pattern2" file.txt
grep -f patterns.txt file.txt
-e → specify multiple patterns
-f → read patterns from a file
Highlighting Matches
grep --color=auto "pattern" file.txt
Highlights the matching text in output
Combining with Other Commands
ps aux | grep "ssh"
ls -l | grep "^d"
Filters command output in pipelines, essential in shell scripting
Common Options Quick Reference
Option Description
-i Case-insensitive
-w Match whole word
-n Show line numbers
-c Count matching lines
-v Invert match
-r / -R Recursive search
-E Extended regex
-F Fixed string (no regex)
-o Print only matching part
-C N Show N lines before & after
-B N Show N lines before
-A N Show N lines after
-q Quiet mode, exit code only
-e Specify multiple patterns
-f Read patterns from a file
--color=auto Highlight matching text
EGREP Command – Technical Reference:
egrep (Extended Global Regular Expression Print) is a variant of grep that supports extended regular expressions (ERE) without needing to escape special characters like +, ?, |, or ().
Note: Modern Linux systems treat egrep as equivalent to grep -E.
Basic Syntax
egrep [options] pattern [file...]
pattern → extended regular expression (ERE)
file → file(s) to search (optional; reads stdin if omitted)
Examples:
egrep "cat|dog" file.txt
echo "hello world" | egrep "hello|world"
Extended Regular Expressions (ERE)
Character Meaning Example
+ One or more occurrences egrep "go+gle" → matches google, gooogle
? Zero or one occurrence egrep "colou?r" → matches color or colour
() Grouping `egrep "(cat
{n,m} At least n, at most m occurrences egrep "a{2,4}" file.txt
Unlike grep, special characters do not need escaping.
Case-Insensitive Search
egrep -i "pattern" file.txt
-i → ignore case
Display Line Numbers
egrep -n "pattern" file.txt
-n → shows line numbers of matches
Invert Match
egrep -v "pattern" file.txt
-v → shows lines not matching the pattern
Counting Matches
egrep -c "pattern" file.txt
-c → counts number of matching lines
Recursive Search
egrep -r "pattern" /path/to/dir
-r / -R → search recursively in directories
Show Context Around Matches
egrep -C 2 "pattern" file.txt # 2 lines before & after
egrep -B 3 "pattern" file.txt # 3 lines before
egrep -A 4 "pattern" file.txt # 4 lines after
Multiple Patterns
egrep -e "pattern1" -e "pattern2" file.txt
egrep -f patterns.txt file.txt
-e → multiple patterns
-f → patterns read from file
Highlight Matches
egrep --color=auto "pattern" file.txt
Highlights matching text in terminal
Only Matching Part of Line
egrep -o "pattern" file.txt
-o → prints only matched text, not the entire line
Quiet Mode
egrep -q "pattern" file.txt
if egrep -q "error" logfile.txt; then echo "Error found!"; fi
-q → suppresses output; only sets exit status
Useful in shell scripts and conditional statements
Combining Options
egrep -i -n -C 2 "pattern" file.txt
Example: case-insensitive, show line numbers, and 2 lines of context
Comparing grep, grep -E, and egrep
Command Supports ERE? Escaping Needed?
grep No Yes, for +, ?, ()
grep -E Yes No
egrep Yes No
Modern Linux: egrep is deprecated, replaced by grep -E. Behavior is identical.
Common Options Quick Reference
Option Description
-i Case-insensitive
-v Invert match (lines not matching)
-c Count matching lines
-n Show line numbers
-r / -R Recursive search
-o Print only matching text
-C N Show N lines of context
-B N Show N lines before match
-A N Show N lines after match
-e Multiple patterns
-f Patterns from a file
--color=auto Highlight matches
-q Quiet mode (exit code only)
ECHO Command – Technical Reference:
The echo command is used to display text, variables, or command output to standard output (screen). It is widely used in shell scripting for printing messages, debugging, formatting output, or logging.
Basic Syntax
echo [options] [string...]
string → text, variables, or command substitution
By default, echo adds a newline at the end
Examples:
echo "Hello World"
name="Alice"
echo "Hello, $name"
echo $((5 + 3)) # Output: 8
Escape Sequences
Use -e to interpret escape sequences:
Escape Meaning
\n Newline
\t Horizontal tab
\\ Backslash
\" Double quote
\a Alert (bell)
\b Backspace
\r Carriage return
Example:
echo -e "Line1\nLine2\nLine3"
echo -e "Column1\tColumn2\tColumn3"
Suppressing Newline
echo -n "Hello "
echo "World"
-n → prevents newline at the end
Output: Hello World on the same line
Displaying Variables
user="Bob"
echo "Current user is $user"
echo "Home directory: $HOME"
$HOME → built-in environment variable
Command Substitution
echo "Today is $(date)"
echo "Files: $(ls)"
Executes commands in $(...) and prints the output
Using Quotes
Double quotes → preserve spaces, allow variable expansion:
name="Alice"
echo "Hello $name"
Single quotes → preserve literal text, no expansion:
echo 'Hello $name' # Prints: Hello $name
Redirection with echo
echo "Hello World" > file.txt # overwrite file
echo "Another line" >> file.txt # append to file
> → overwrite
>> → append
Printing Special Characters
echo -e "Tab\tNewline\nBackslash\\Quote\""
Handles tabs, newlines, backslashes, quotes, etc.
Using echo in Scripts
#!/bin/bash
echo "Script started"
name="Alice"
echo "Hello, $name"
echo "Listing files:"
echo "$(ls)"
Prints messages, variables, and command output
Common Options Quick Reference
Option Description
-e Enable interpretation of backslash escapes
-n Do not print trailing newline
-E Disable interpretation of backslash escapes (default)
Practical Examples
Multi-line message:
echo -e "Welcome\n================\nUser: $USER\nDate: $(date)"
Table with tabs:
echo -e "Name\tAge\tCity\nAlice\t25\tNY\nBob\t30\tLA"
Debugging in scripts:
echo "Variable x = $x"
Appending to a log file:
echo "$(date): Script executed successfully" >> script.log
PRINT / printf Command – Technical Reference:
Shell scripting does not have a universal print command like Python. Most printing is done using echo or printf. Some shells (e.g., ksh, zsh) also support a print command.
Printing options in shell scripting:
echo – simple printing, widely used
printf – formatted, portable, similar to C's printf
print – shell-specific (ksh, zsh)
Using echo
echo "Hello World"
echo -e "Hello\tWorld\nNew Line"
-e → interpret escape sequences
-n → suppress newline
Example:
echo -e "Name:\tAlice\nAge:\t25"
Using printf (Advanced / Portable)
printf is more powerful than echo and preferred for formatted output.
Syntax
printf "format" [arguments...]
format → string with placeholders (%s, %d, %f, etc.)
arguments → values replacing placeholders
Examples
printf "Name: %s\nAge: %d\n" "Alice" 25
# Output:
# Name: Alice
# Age: 25
printf "Pi: %.2f\n" 3.14159
# Output: Pi: 3.14
printf "%-10s %5d\n" "Alice" 25
# Output: Alice 25
# %-10s → left-align text, width 10
# %5d → right-align integer, width 5
Using print (ksh / zsh)
Not POSIX standard; only in ksh or zsh
Can replace echo in these shells
Syntax
print [options] string
Examples
print "Hello World"
print -n "Hello" # suppress newline
print " World"
print -r "Text with \n no escape"
-n → suppress newline
-r → raw, do not interpret backslash escapes
Comparison Table
Command Supports Escape Sequences Formatted Output Notes
echo Yes, with -e No Simple, most used
printf Yes, always Yes Preferred for complex formatting
print Optional (-r) Limited Shell-specific (ksh/zsh)
Examples in Shell Scripting
#!/bin/bash
# Using echo
name="Alice"
echo "Hello, $name"
# Using printf
age=25
printf "Name: %s, Age: %d\n" "$name" "$age"
# Using print (ksh/zsh)
print "Hello $name"
DIFF Command – Technical Reference:
The diff command compares two files line by line and shows their differences. It is widely used for version control, debugging, and script automation.
Basic Syntax
diff [options] file1 file2
file1, file2 → files to compare
Default output shows lines that differ using < and > symbols
Example:
# file1.txt
apple
banana
cherry
# file2.txt
apple
blueberry
cherry
diff file1.txt file2.txt
# Output:
2c2
< banana
---
> blueberry
2c2 → line 2 changed
< → line from file1
> → line from file2
Common Symbols in Output
Symbol Meaning
a added line
d deleted line
c changed line
< line from first file
> line from second file
Ignore Differences
Case-insensitive:
diff -i file1.txt file2.txt
Ignore whitespace:
diff -w file1.txt file2.txt # all spaces
diff -b file1.txt file2.txt # changes in number of spaces
diff -B file1.txt file2.txt # blank lines
Side-by-Side Comparison
diff -y file1.txt file2.txt
diff -y --suppress-common-lines file1.txt file2.txt # hide unchanged lines
-y → side-by-side display
Unified and Context Formats
Unified format:
diff -u file1.txt file2.txt
Shows context lines around changes; used in git patches
@@ -1,3 +1,3 @@
apple
-banana
+blueberry
cherry
Context format:
diff -c file1.txt file2.txt
Older style, shows surrounding lines
Recursive Comparison
diff -r dir1 dir2
Compares directories recursively
Shows differences for all files inside directories
Suppressing Common Lines
diff --suppress-common-lines file1.txt file2.txt
Only shows differing lines, reduces clutter
Exit Status Codes
Can be used in scripts to detect differences:
if diff file1.txt file2.txt > /dev/null; then
echo "Files are identical"
else
echo "Files differ"
fi
Exit codes:
Code Meaning
0 files are identical
1 files differ
>1 error
Comparing Binary Files
diff --binary file1.bin file2.bin
Compares binary files; often cmp is better for strict binary comparison
Common Options Quick Reference
Option Description
-i Ignore case
-w Ignore all whitespace
-b Ignore changes in number of spaces
-B Ignore blank lines
-y Side-by-side comparison
--suppress-common-lines Hide unchanged lines
-u Unified diff format
-c Context diff format
-r Recursive directory comparison
--brief Only report if files differ
Practical Examples
Check if two files are different:
if diff -q file1.txt file2.txt > /dev/null; then
echo "Files are identical"
else
echo "Files differ"
fi
Create a patch file:
diff -u old_version.txt new_version.txt > patch.diff
Compare directories recursively:
diff -r dir1/ dir2/
EXIT Command – Technical Reference:
The exit command is used in shell scripting to terminate a script or function and return a numeric exit status to the shell or calling process. Exit codes help indicate success or failure.
Basic Syntax
exit [n]
n → optional exit status (integer 0–255)
0 → success
Non-zero → failure
If omitted, exit returns the status of the last executed command
Examples
Exit with Success
#!/bin/bash
echo "Script started"
exit 0
echo "This will not run"
Output:
Script started
Script stops immediately after exit 0
Exit with Failure
#!/bin/bash
echo "Something went wrong!"
exit 1
Check exit status afterward:
echo $?
# Output: 1
Check Exit Status of Previous Command
ls /tmp > /dev/null
echo "Exit status of ls: $?"
Exit Codes:
Code Meaning
0 Success
1–255 Error / failure
Exit After an Error
Automatically terminate the script when a command fails:
#!/bin/bash
set -e
cp file1.txt /nonexistent/path
echo "This line will not execute"
set -e → exits immediately if a command fails
Exit from a Function
return → exit function only
exit → stops the entire script
#!/bin/bash
my_function() {
echo "Inside function"
exit 2 # stops script
echo "This won't run"
}
my_function
echo "This won't run either"
Custom Exit Codes
SUCCESS=0
ERR_NO_FILE=10
ERR_INVALID=20
if [ ! -f "$1" ]; then
echo "File not found!"
exit $ERR_NO_FILE
fi
Best Practices
Use exit 0 for success
Use exit 1–255 for specific errors
Document exit codes clearly in scripts
Example Header:
Exit codes:
0 – Success
1 – Invalid input
2 – File not found