cheetsheetz/BASH.md

443 lines
6.1 KiB
Markdown

# Comprehensive BASH Cheat Sheet
## Table of Contents
1. [Basic Commands](#basic-commands)
2. [Variables](#variables)
3. [Conditionals](#conditionals)
4. [Loops](#loops)
5. [Functions](#functions)
6. [File Operations](#file-operations)
7. [Text Processing](#text-processing)
8. [Pipelines](#pipelines)
9. [Redirection](#redirection)
10. [Processes](#processes)
11. [Environment Variables](#environment-variables)
12. [User Input](#user-input)
13. [Error Handling](#error-handling)
14. [Scripting](#bash-scripting-examples)
15. [Functions with Parameters](#functions-with-parameters)
16. [Arrays](#arrays)
17. [Error Handling and Logging](#error-handling-and-logging)
18. [Reading from Files](#reading-from-files)
19. [Command-Line Arguments](#command-line-arguments)
20. [Regular Expressions](#regular-expressions)
21. [Math Operations](#math-operations)
22. [Advanced I/O Redirection](#advanced-io-redirection)
23. [Advanced Control Structures](#advanced-control-structures)
24. [Job Control](#job-control)
25. [Signals and Traps](#signals-and-traps)
26. [Advanced Process Management](#advanced-process-management)
## Basic Commands
### Echo
```bash
echo "Hello, World!"
```
### Print Working Directory
```bash
pwd
```
### List Files
```bash
ls
```
### Change Directory
```bash
cd /path/to/directory
```
## Variables
### Assigning Variables
```bash
variable_name="value"
```
### Accessing Variables
```bash
echo $variable_name
```
## Conditionals
### If Statement
```bash
if [ condition ]; then
# Commands
fi
```
### If-Else Statement
```bash
if [ condition ]; then
# Commands for true condition
else
# Commands for false condition
fi
```
### Case Statement
```bash
case "$variable" in
pattern1)
# Commands
;;
pattern2)
# Commands
;;
*)
# Default case
;;
esac
```
## Loops
### For Loop
```bash
for item in list; do
# Commands
done
```
### While Loop
```bash
while [ condition ]; do
# Commands
done
```
### Until Loop
```bash
until [ condition ]; do
# Commands
done
```
## Functions
```bash
function_name() {
# Commands
}
# Call the function
function_name
```
## File Operations
### Create a File
```bash
touch filename
```
### Create a Directory
```bash
mkdir directory_name
```
### Copy File
```bash
cp source_file destination
```
### Move/Rename File
```bash
mv old_filename new_filename
```
### Remove/Delete File
```bash
rm filename
```
## Text Processing
### Concatenate Files
```bash
cat file1 file2
```
### Count Lines in a File
```bash
wc -l filename
```
### Grep (Search)
```bash
grep "pattern" filename
```
### Sed (Stream Editor)
```bash
sed 's/old_pattern/new_pattern/' filename
```
## Pipelines
### Pipe Operator
```bash
command1 | command2
```
### Command Substitution
```bash
result=$(command)
```
## Redirection
### Standard Output (stdout)
```bash
command > output.txt
```
### Standard Error (stderr)
```bash
command 2> error.txt
```
### Input Redirection
```bash
command < input.txt
```
## Processes
### List Running Processes
```bash
ps
```
### Kill Process
```bash
kill process_id
```
## Environment Variables
### Display All Variables
```bash
printenv
```
### Set Environment Variable
```bash
export MY_VARIABLE="value"
```
## User Input
### Read User Input
```bash
read -p "Enter your name: " name
```
## Error Handling
### Exit with Error Code
```bash
exit 1
```
### Trap Command
```bash
trap "echo 'Error occurred!'" ERR
```
## BASH Scripting Examples
[Back to Top](#table-of-contents)
1. [Functions with Parameters](#functions-with-parameters)
2. [Arrays](#arrays)
3. [Error Handling and Logging](#error-handling-and-logging)
4. [Reading from Files](#reading-from-files)
5. [Command-Line Arguments](#command-line-arguments)
6. [Regular Expressions](#regular-expressions)
7. [Math Operations](#math-operations)
8. [Advanced I/O Redirection](#advanced-io-redirection)
9. [Advanced Control Structures](#advanced-control-structures)
10. [Job Control](#job-control)
11. [Signals and Traps](#signals-and-traps)
12. [Advanced Process Management](#advanced-process-management)
## Functions with Parameters
```bash
function greet() {
echo "Hello, $1!"
}
greet "John"
```
## Arrays
```bash
# Declare an array
my_array=("apple" "banana" "cherry")
# Access an element
echo ${my_array[1]}
# Iterate over array elements
for item in "${my_array[@]}"; do
echo $item
done
```
## Error Handling and Logging
```bash
# Redirect stdout and stderr to a log file
command > log.txt 2>&1
# Check the exit status of a command
if [ $? -eq 0 ]; then
echo "Command succeeded."
else
echo "Command failed."
fi
```
## Reading from Files
```bash
# Read lines from a file
while IFS= read -r line; do
echo "$line"
done < "filename.txt"
```
## Command-Line Arguments
```bash
# Access command-line arguments
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
```
## Regular Expressions
```bash
# Check if a string matches a pattern
if [[ "string" =~ ^[0-9]+$ ]]; then
echo "String is a number."
fi
```
## Math Operations
```bash
# Perform arithmetic operations
result=$((5 + 3))
echo "Result: $result"
```
## Advanced I/O Redirection
```bash
# Redirect stdin from a file
command < input.txt
# Append to a file
echo "New content" >> output.txt
```
## Advanced Control Structures
```bash
# Select Case statement
fruit="apple"
case $fruit in
"apple")
echo "It's an apple."
;;
"banana")
echo "It's a banana."
;;
*)
echo "Unknown fruit."
;;
esac
```
## Job Control
```bash
# Run a command in the background
command &
# List background jobs
jobs
# Bring a background job to the foreground
fg %1
```
## Signals and Traps
```bash
# Trap a signal
trap 'echo "Signal received"; cleanup_function' INT TERM
# Send a signal to a process
kill -TERM process_id
```
## Advanced Process Management
```bash
# Get the process ID of a running command
pid=$(pgrep process_name)
# Check if a process is running
if ps -p $pid > /dev/null; then
echo "Process is running."
else
echo "Process is not running."
fi
```