cheetsheetz/BASH.md

6.1 KiB

Comprehensive BASH Cheat Sheet

Table of Contents

  1. Basic Commands
  2. Variables
  3. Conditionals
  4. Loops
  5. Functions
  6. File Operations
  7. Text Processing
  8. Pipelines
  9. Redirection
  10. Processes
  11. Environment Variables
  12. User Input
  13. Error Handling
  14. Scripting
  15. Functions with Parameters
  16. Arrays
  17. Error Handling and Logging
  18. Reading from Files
  19. Command-Line Arguments
  20. Regular Expressions
  21. Math Operations
  22. Advanced I/O Redirection
  23. Advanced Control Structures
  24. Job Control
  25. Signals and Traps
  26. Advanced Process Management

Basic Commands

Echo

echo "Hello, World!"

Print Working Directory

pwd

List Files

ls

Change Directory

cd /path/to/directory

Variables

Assigning Variables

variable_name="value"

Accessing Variables

echo $variable_name

Conditionals

If Statement

if [ condition ]; then
    # Commands
fi

If-Else Statement

if [ condition ]; then
    # Commands for true condition
else
    # Commands for false condition
fi

Case Statement

case "$variable" in
    pattern1)
        # Commands
        ;;
    pattern2)
        # Commands
        ;;
    *)
        # Default case
        ;;
esac

Loops

For Loop

for item in list; do
    # Commands
done

While Loop

while [ condition ]; do
    # Commands
done

Until Loop

until [ condition ]; do
    # Commands
done

Functions

function_name() {
    # Commands
}

# Call the function
function_name

File Operations

Create a File

touch filename

Create a Directory

mkdir directory_name

Copy File

cp source_file destination

Move/Rename File

mv old_filename new_filename

Remove/Delete File

rm filename

Text Processing

Concatenate Files

cat file1 file2

Count Lines in a File

wc -l filename
grep "pattern" filename

Sed (Stream Editor)

sed 's/old_pattern/new_pattern/' filename

Pipelines

Pipe Operator

command1 | command2

Command Substitution

result=$(command)

Redirection

Standard Output (stdout)

command > output.txt

Standard Error (stderr)

command 2> error.txt

Input Redirection

command < input.txt

Processes

List Running Processes

ps

Kill Process

kill process_id

Environment Variables

Display All Variables

printenv

Set Environment Variable

export MY_VARIABLE="value"

User Input

Read User Input

read -p "Enter your name: " name

Error Handling

Exit with Error Code

exit 1

Trap Command

trap "echo 'Error occurred!'" ERR

BASH Scripting Examples

Back to Top

  1. Functions with Parameters
  2. Arrays
  3. Error Handling and Logging
  4. Reading from Files
  5. Command-Line Arguments
  6. Regular Expressions
  7. Math Operations
  8. Advanced I/O Redirection
  9. Advanced Control Structures
  10. Job Control
  11. Signals and Traps
  12. Advanced Process Management

Functions with Parameters

function greet() {
    echo "Hello, $1!"
}

greet "John"

Arrays

# 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

# 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

# Read lines from a file
while IFS= read -r line; do
    echo "$line"
done < "filename.txt"

Command-Line Arguments

# Access command-line arguments
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

Regular Expressions

# Check if a string matches a pattern
if [[ "string" =~ ^[0-9]+$ ]]; then
    echo "String is a number."
fi

Math Operations

# Perform arithmetic operations
result=$((5 + 3))
echo "Result: $result"

Advanced I/O Redirection

# Redirect stdin from a file
command < input.txt

# Append to a file
echo "New content" >> output.txt

Advanced Control Structures

# 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

# Run a command in the background
command &

# List background jobs
jobs

# Bring a background job to the foreground
fg %1

Signals and Traps

# Trap a signal
trap 'echo "Signal received"; cleanup_function' INT TERM

# Send a signal to a process
kill -TERM process_id

Advanced Process Management

# 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