Skip to content

Latest commit

 

History

History
192 lines (147 loc) · 2.79 KB

bash_cheatsheet.md

File metadata and controls

192 lines (147 loc) · 2.79 KB

Bash Scripting Cheatsheet

Basic Script Structure

#!/bin/bash

# Your code here

Variables

# Declaring variables
name="John"
age=30

# Using variables
echo "My name is $name and I'm $age years old"

# Command substitution
current_date=$(date +%Y-%m-%d)

# Arithmetic operations
result=$((5 + 3))

Conditionals

# If statement
if [ "$a" -eq "$b" ]; then
    echo "a is equal to b"
elif [ "$a" -gt "$b" ]; then
    echo "a is greater than b"
else
    echo "a is less than b"
fi

# Case statement
case "$variable" in
    pattern1) command1;;
    pattern2) command2;;
    *) default_command;;
esac

# Check number of command line arguments
if [ "$#" -eq 2 ]; then
    echo "Exactly two arguments provided"
elif [ "$#" -lt 2 ]; then
    echo "Less than two arguments provided"
elif [ "$#" -ge 2 ]; then
    echo "Two or more arguments provided"
fi

Loops

# For loop
for i in {1..5}; do
    echo $i
done

# While loop
counter=0
while [ $counter -lt 5 ]; do
    echo $counter
    ((counter++))
done

# Until loop
until [ $counter -ge 5 ]; do
    echo $counter
    ((counter++))
done

Functions

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

greet "World"

Input/Output

# Read user input
read -p "Enter your name: " name

# Write to file
echo "Some text" > file.txt

# Append to file
echo "More text" >> file.txt

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

Arrays

# Declare an array
fruits=("apple" "banana" "cherry")

# Access array elements
echo ${fruits[0]}  # First element
echo ${fruits[@]}  # All elements

# Array length
echo ${#fruits[@]}

String Manipulation

string="Hello, World!"

# String length
echo ${#string}

# Substring
echo ${string:7:5}  # Extracts "World"

# Replace
echo ${string/World/Universe}

Command Line Arguments

# Access arguments
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"

# Check number of arguments
if [ "$#" -eq 0 ]; then
    echo "No arguments provided"
elif [ "$#" -eq 1 ]; then
    echo "One argument provided"
elif [ "$#" -ge 2 ]; then
    echo "Two or more arguments provided"
fi

Error Handling

# Exit on error
set -e

# Custom error handling
error() {
    echo "Error: $1" >&2
    exit 1
}

# Usage
if [ "$#" -ne 2 ]; then
    error "Two arguments required"
fi

Useful Commands

# Check if file exists
if [ -f "$file" ]; then
    echo "File exists"
fi

# Check if directory exists
if [ -d "$dir" ]; then
    echo "Directory exists"
fi

# Check if command exists
if command -v jq &> /dev/null; then
    echo "jq is installed"
fi

# Print a # character across the terminal. (visual separator)
printf -v separator '%*s' $(tput cols) '' && echo "${separator// /#}"