Category: Bash

  • macOS User Login and Uptime Report Bash Script

    This script provides system administrators with a clear overview of the system’s current uptime and detailed last login information for human user accounts (UID ≥ 500). It displays key details such as the terminal, login date, login time, and session status for each account.

    Click to view script…
    #!/bin/bash
    # Title: Detailed macOS User Last Login Checker with System Uptime
    # Description:
    # This script lists human user accounts (UID ≥ 500) on macOS and displays detailed information about their last login session.
    # It also shows the current system uptime at the top.
    #
    # The output includes:
    #   - System Uptime: How long the machine has been running since the last boot.
    #   - Username     : The account name.
    #   - Terminal     : The terminal device used during login.
    #   - Login Date   : The date of the login (Day Month Date).
    #   - Login Time   : The time when the login occurred.
    #   - Login Status : Indicates if the session is still active or has ended.
    #
    # Note: "Never logged in" is shown if no login record exists.
    #
    # Retrieve and display system uptime
    systemUptime=$(uptime)
    echo "System Uptime: $systemUptime"
    echo ""
    
    # Print header for the login details
    echo "Username | Terminal | Login Date       | Login Time | Login Status"
    echo "---------------------------------------------------------------------"
    
    # List users with their UniqueIDs and process each one.
    dscl . -list /Users UniqueID | while read username uid; do
        if [ "$uid" -ge 500 ]; then
            # Retrieve the most recent login record for the user
            loginInfo=$(last -1 "$username" | head -n 1)
            
            # Check if there is a valid login record
            if echo "$loginInfo" | grep -q "wtmp begins"; then
                echo "$username |    -     |       -        |     -    | Never logged in"
            else
                # Parse the login record:
                #   Field 1: Username (redundant here)
                #   Field 2: Terminal (e.g., ttys000)
                #   Fields 3-5: Login Date (e.g., "Mon Feb 17")
                #   Field 6: Login Time (e.g., "05:44")
                #   Fields 7+: Login Status (e.g., "still logged in" or the session end time)
                terminal=$(echo "$loginInfo" | awk '{print $2}')
                login_date=$(echo "$loginInfo" | awk '{print $3, $4, $5}')
                login_time=$(echo "$loginInfo" | awk '{print $6}')
                login_status=$(echo "$loginInfo" | cut -d' ' -f7-)
                
                # Output the parsed details in a table-like format
                printf "%-8s | %-8s | %-16s | %-10s | %s\n" "$username" "$terminal" "$login_date" "$login_time" "$login_status"
            fi
        fi
    done
    
    # Legend:
    #   System Uptime - How long the system has been running since the last boot.
    #   Username      - The account name.
    #   Terminal      - The terminal device used during login.
    #   Login Date    - The date of the login (Day Month Date).
    #   Login Time    - The time of the login.
    #   Login Status  - The current status of the login session.
  • Enhanced macOS User Account Details Bash Script

    This Bash script retrieves and displays detailed information for all human user accounts (UID ≥ 500) on macOS, including the username, UID, admin privileges, full name, home directory, and default shell. It provides a clear and organized summary that is useful for system administrators to review and manage user configurations.

    Click to view script…
    #!/bin/bash
    # This script lists user accounts (UID >= 500) and shows additional details:
    # Username, UID, Admin Privileges (true/false), Full Name, Home Directory, and Shell
    
    # Print header for clarity
    echo "Username : UID : Has Admin Privileges : Full Name : Home Directory : Shell"
    
    # List all users with their UniqueID and process each line
    dscl . -list /Users UniqueID | while read username uid; do
        # Only process accounts with UID >= 500 (typically non-system, human user accounts)
        if [ "$uid" -ge 500 ]; then
            # Check if the user belongs to the 'admin' group
            if id -Gn "$username" 2>/dev/null | grep -qw "admin"; then
                adminFlag="true"
            else
                adminFlag="false"
            fi
    
            # Get the user's full name (if set). The command outputs a line like "RealName: John Doe"
            fullName=$(dscl . -read /Users/"$username" RealName 2>/dev/null | sed 's/RealName: //')
            
            # Get the user's home directory
            homeDir=$(dscl . -read /Users/"$username" NFSHomeDirectory 2>/dev/null | sed 's/NFSHomeDirectory: //')
            
            # Get the user's default shell
            shell=$(dscl . -read /Users/"$username" UserShell 2>/dev/null | sed 's/UserShell: //')
            
            # Output the collected information in a clear, colon-separated format
            echo "$username : $uid : $adminFlag : $fullName : $homeDir : $shell"
        fi
    done
  • macOS App Version Finder Bash Script

    This interactive script scans your /Applications and ~/Applications directories to list installed apps, allowing you to select one and view its version. It supports multiple searches and includes a built-in quit option for easy use.

    Click to view script…
    #!/bin/bash
    # Interactive App Version Finder for macOS with multi-search capability
    
    # Define directories to search for applications.
    APP_DIRS=("/Applications" "$HOME/Applications")
    
    # Initialize an array to store found apps.
    apps=()
    
    # Search for .app directories (non-recursive) in defined directories.
    for dir in "${APP_DIRS[@]}"; do
      if [ -d "$dir" ]; then
        while IFS= read -r -d $'\0' app; do
          apps+=("$app")
        done < <(find "$dir" -maxdepth 1 -type d -name "*.app" -print0)
      fi
    done
    
    # Check if any apps were found.
    if [ ${#apps[@]} -eq 0 ]; then
      echo "No applications found in ${APP_DIRS[*]}."
      exit 1
    fi
    
    # Main interactive loop.
    while true; do
      echo ""
      echo "Available Applications:"
      for i in "${!apps[@]}"; do
        echo "[$i] $(basename "${apps[$i]}")"
      done
      echo "[q] Quit"
      
      read -p "Enter the number of the app to check its version (or 'q' to quit): " input
    
      # Check for the quit option.
      if [[ "$input" =~ ^[Qq]$ ]]; then
        echo "Exiting."
        exit 0
      fi
    
      # Validate input is a number and within range.
      if ! [[ "$input" =~ ^[0-9]+$ ]] || [ "$input" -ge "${#apps[@]}" ]; then
        echo "Invalid selection. Please try again."
        continue
      fi
    
      APP_PATH="${apps[$input]}"
      APP_NAME=$(basename "$APP_PATH" .app)
    
      # Retrieve the version information from the app's Info.plist.
      VERSION=$(defaults read "$APP_PATH/Contents/Info" CFBundleShortVersionString 2>/dev/null)
    
      if [ -z "$VERSION" ]; then
        echo "Version information not found for $APP_NAME."
      else
        echo "$APP_NAME version: $VERSION"
      fi
    
      echo ""
      # Ask if the user wants to perform another search.
      read -p "Do you want to search for another app? (y/n): " answer
      if [[ ! "$answer" =~ ^[Yy]$ ]]; then
        echo "Exiting."
        exit 0
      fi
    done
  • Interactive macOS Countdown Timer Bash Script

    This Bash script creates a countdown timer that either accepts the duration in seconds as a command-line argument or prompts the user for input. It displays the remaining time in the Terminal and sends a native macOS notification when the countdown completes.

    Click to view script…
    #!/bin/bash
    # Simple Countdown Timer for macOS with Interactive Input
    
    # Check if a time (in seconds) was provided as an argument
    if [ $# -eq 0 ]; then
        # Prompt the user for input if no argument is given
        read -p "Enter number of seconds for the countdown: " TIME_LEFT
    else
        TIME_LEFT=$1
    fi
    
    # Validate that the input is a positive integer
    if ! [[ $TIME_LEFT =~ ^[0-9]+$ ]] ; then
        echo "Error: Please enter a positive integer for seconds." >&2
        exit 1
    fi
    
    # Countdown loop
    while [ $TIME_LEFT -gt 0 ]; do
        echo -ne "Time left: ${TIME_LEFT} second(s) \r"
        sleep 1
        ((TIME_LEFT--))
    done
    
    # Move to a new line after the countdown
    echo -e "\nTime's up!"
    
    # Display a macOS notification using osascript
    osascript -e 'display notification "Countdown Complete!" with title "Timer"'
  • Mac System Specs and Performance Dashboard Bash Script

    This script provides an organized summary of your Mac’s system information and performance metrics—including OS details, CPU specifications, memory size, disk usage, uptime, and battery status.

    Click to view script…
    #!/bin/bash
    # system_specs.sh - Display Mac system specs and performance info
    
    # Clear the terminal for a fresh display
    clear
    
    echo "======================================"
    echo "   Mac System Specs and Performance   "
    echo "======================================"
    
    # Operating System Information
    os_name=$(sw_vers -productName)
    os_version=$(sw_vers -productVersion)
    build_version=$(sw_vers -buildVersion)
    echo "Operating System: $os_name $os_version (Build $build_version)"
    
    # Computer Name (if set)
    computer_name=$(scutil --get ComputerName 2>/dev/null)
    if [ -n "$computer_name" ]; then
        echo "Computer Name: $computer_name"
    fi
    
    echo "--------------------------------------"
    
    # CPU Information
    cpu_brand=$(sysctl -n machdep.cpu.brand_string)
    physical_cpu=$(sysctl -n hw.physicalcpu)
    logical_cpu=$(sysctl -n hw.logicalcpu)
    echo "CPU: $cpu_brand"
    echo "Physical Cores: $physical_cpu"
    echo "Logical Cores: $logical_cpu"
    
    echo "--------------------------------------"
    
    # Memory (RAM) Information
    mem_bytes=$(sysctl -n hw.memsize)
    # Convert bytes to gigabytes (1GB = 1073741824 bytes)
    mem_gb=$(echo "scale=2; $mem_bytes/1073741824" | bc)
    echo "Memory (RAM): $mem_gb GB"
    
    echo "--------------------------------------"
    
    # Disk Usage for the Root Partition
    echo "Disk Usage (Root Partition):"
    # Display header and the line for '/' partition
    df -h / | awk 'NR==1 || $NF=="/"'
    echo "--------------------------------------"
    
    # Uptime and Load Average
    echo "Uptime and Load Average:"
    uptime
    echo "--------------------------------------"
    
    # Battery Information (if available)
    if command -v pmset &> /dev/null; then
        battery_info=$(pmset -g batt | head -1)
        echo "Battery Info: $battery_info"
    fi
    
    echo "======================================"
  • Gather Weather Bash Script

    This Bash script uses the wttr.in service to automatically fetch and display your current weather based on your IP geolocation, directly in your macOS terminal. It first checks for the curl utility and then outputs the ASCII weather forecast

    Click to view script…
    #!/bin/bash
    # current_weather.sh - Query current weather for your current location on macOS.
    # This script uses the wttr.in API to retrieve weather information based on your IP geolocation.
    # Usage: ./current_weather.sh
    
    # Define colors for output
    BLUE='\033[0;34m'
    NC='\033[0m'  # No Color
    
    # Ensure curl is installed
    if ! command -v curl &>/dev/null; then
      echo "Error: curl is not installed. Please install curl to use this script."
      exit 1
    fi
    
    echo -e "${BLUE}Fetching current weather for your location...${NC}"
    weather=$(curl -s wttr.in)
    
    if [ -z "$weather" ]; then
      echo "Error: Unable to retrieve weather information."
      exit 1
    fi
    
    echo "$weather"
  • macOS Public IP Checker Bash Script

    This Bash script uses curl to query ifconfig.me for your public IP address and then displays it in the Terminal on macOS.

    Click to view script…
    #!/bin/bash
    # check_public_ip.command - Display your public IP address on macOS
    # This script uses curl to query ifconfig.me, which returns your public IP address.
    # Usage: ./check_public_ip.command
    
    # Check if curl is installed
    if ! command -v curl &>/dev/null; then
      echo "Error: curl is not installed. Please install curl to use this script."
      exit 1
    fi
    
    echo "Fetching public IP address..."
    public_ip=$(curl -s ifconfig.me)
    
    if [ -z "$public_ip" ]; then
      echo "Error: Unable to retrieve public IP address."
      exit 1
    fi
    
    echo "Your public IP address is: $public_ip"
  • macOS Network Diagnostics & Information Tool Bash Script

    This Bash script collects detailed network information on a macOS system by querying system utilities (like routeifconfig, and ipconfig) and formatting the output with colored text for easy reading. It reports data such as the default gateway, active interface, IP address, subnet mask, broadcast address, MAC address, DNS servers, public IP, and average ping latency

    Click to view script…
    #!/bin/bash
    # netinfo_detailed.sh - Detailed network information for macOS
    
    # Define colors for output (ANSI escape codes)
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    BLUE='\033[0;34m'
    NC='\033[0m' # No Color
    
    echo -e "${BLUE}Gathering default route information...${NC}"
    
    # Get the default gateway and active interface from the routing table.
    default_route=$(route -n get default 2>/dev/null)
    gateway=$(echo "$default_route" | awk '/gateway/ {print $2}')
    iface=$(echo "$default_route" | awk '/interface/ {print $2}')
    
    if [ -z "$iface" ]; then
      echo -e "${RED}Error: No active network interface found. Are you connected to a network?${NC}"
      exit 1
    fi
    
    echo -e "${GREEN}Default Interface: ${NC}$iface"
    echo -e "${GREEN}Gateway: ${NC}$gateway"
    
    # Get the IP address for the active interface.
    ip=$(ipconfig getifaddr "$iface")
    echo -e "${GREEN}IP Address: ${NC}$ip"
    
    # Retrieve the subnet mask in hexadecimal from ifconfig.
    # Expected format is like: "inet 192.168.1.2 netmask 0xffffff00 broadcast 192.168.1.255"
    mask_hex=$(ifconfig "$iface" | awk '/inet / {print $4}')
    # Remove any leading "0x" using sed so that we have exactly 8 hex digits.
    mask_hex=$(echo "$mask_hex" | sed 's/^0x//')
    if [ ${#mask_hex} -ne 8 ]; then
      echo -e "${RED}Unexpected netmask format: $mask_hex${NC}"
      netmask="Unknown"
    else
      mask1=$((16#${mask_hex:0:2}))
      mask2=$((16#${mask_hex:2:2}))
      mask3=$((16#${mask_hex:4:2}))
      mask4=$((16#${mask_hex:6:2}))
      netmask="${mask1}.${mask2}.${mask3}.${mask4}"
    fi
    echo -e "${GREEN}Subnet Mask: ${NC}$netmask"
    
    # Get the broadcast address from ifconfig output.
    broadcast=$(ifconfig "$iface" | awk '/broadcast/ {print $4}')
    echo -e "${GREEN}Broadcast Address: ${NC}$broadcast"
    
    # Get the MAC (hardware) address of the interface.
    mac=$(ifconfig "$iface" | awk '/ether/ {print $2}')
    echo -e "${GREEN}MAC Address: ${NC}$mac"
    
    # Retrieve DNS servers from /etc/resolv.conf.
    dns_servers=$(grep 'nameserver' /etc/resolv.conf | awk '{print $2}' | tr '\n' ' ')
    echo -e "${GREEN}DNS Servers: ${NC}$dns_servers"
    
    # Get the public IP address using an external service.
    public_ip=$(curl -s ifconfig.me)
    echo -e "${GREEN}Public IP Address: ${NC}$public_ip"
    
    # Perform a ping test to google.com and extract the average latency.
    echo -e "${BLUE}Performing ping test to google.com...${NC}"
    ping_result=$(ping -c 3 google.com 2>/dev/null)
    avg_rtt=$(echo "$ping_result" | tail -1 | awk -F'/' '{print $5}')
    if [ -n "$avg_rtt" ]; then
      echo -e "${GREEN}Average Latency (ping): ${NC}${avg_rtt} ms"
    else
      echo -e "${RED}Ping test failed.${NC}"
    fi
    
    echo -e "${BLUE}Detailed network information gathered successfully.${NC}"