Script Guide: Clearing Browser Cache on macOS with a Bash Script 

Efficient management of browser cache is critical for IT professionals and managed service providers (MSPs) striving to optimize system performance and ensure seamless user experiences. For macOS systems, managing browser cache across multiple users and browsers can be cumbersome. Enter the Bash script outlined here, designed to simplify and automate cache clearing tasks for IT administrators.

Understanding the Script’s Background

Browser cache stores temporary data to speed up browsing but can lead to issues like outdated content display or storage inefficiencies if not managed properly. For IT professionals managing multiple systems, clearing caches becomes an essential maintenance task.

This script is a powerful tool for:

  1. Automating Cache Management: Reducing manual intervention.
  2. Streamlining Multi-Browser Operations: Supporting Chrome, Firefox, Safari, and Edge.
  3. Multi-User Compatibility: Clearing cache for one or more user accounts on macOS devices.
  4. Forceful Execution: Ensuring browsers are closed before cache clearance to avoid conflicts.

IT professionals in MSP environments can particularly benefit by integrating this script into routine maintenance workflows, saving time and effort.

The Script:

#!/usr/bin/env bash

# Description: Clears the browser cache for users on a Mac.
#   By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
#   Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
#   Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
#   Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
#   Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
#   Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
#   Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
#   EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#
# Parameter UserName: --UserName "User1,User2"
#   The names of the users to clear the cache for. If not specified, clears the current user's cache.
#
# Parameter Browser: --Browser "Chrome"
#   Clears the cache for the specified browser. If not specified, No browser will be cleared.
#   Valid options are "Chrome", "Firefox", "Edge", "Safari" or multiple browsers separated by a comma. For example, "Chrome,Firefox".
#
# Parameter Force: --Force
#   Will force close the selected browser before clearing the cache.

# These are all our preset parameter defaults. You can set these = to something if you would prefer the script defaults to a certain parameter value.
_arg_userNames=
_arg_browser=
_arg_force=

# Help text function for when invalid input is encountered
print_help() {
    printf '\n\n%s\n\n' 'Usage: [--UserName|-u <arg>] [--Browser|-b <arg>] [--Force|-f] [--help|-h]'
    printf '%s\n' 'Preset Parameter: --UserName "User1,User2"'
    printf '\t%s\n' "The names of the users to clear the cache for. If not specified, clears the current user's cache."
    printf '%s\n' 'Preset Parameter: --Browser "Chrome"'
    printf '\t%s\n' "Clears the cache for the specified browser. Separate multiple browsers with a comma. If not specified, No browser will be cleared."
    printf '\t%s\n' "Valid options are 'Chrome', 'Firefox', 'Edge', 'Safari'."
    printf '%s\n' 'Preset Parameter: --Force'
    printf '\t%s\n' "Will force close the selected browser before clearing the cache."
    printf '\n%s\n' 'Preset Parameter: --help'
    printf '\t%s\n' "Displays this help menu."
}

# Determines whether or not help text is necessary and routes the output to stderr
die() {
    local _ret="${2:-1}"
    echo "$1" >&2
    test "${_PRINT_HELP:-no}" = yes && print_help >&2
    exit "${_ret}"
}

# Grabbing the parameters and parsing through them.
parse_commandline() {
    while test $# -gt 0; do
        _key="$1"
        case "$_key" in
        -u | --UserName | --Username)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_userNames=$2
            shift
            ;;
        --UserName=*)
            _arg_userNames="${_key##--UserNames=}"
            ;;
        -b | -Browser | --Browser)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_browser=$2
            shift
            ;;
        --Browser=*)
            _arg_browser="${_key##--Browser=}"
            ;;
        -f | --Force)
            _arg_force="true"
            ;;
        --help | -h)
            _PRINT_HELP=yes die 0
            ;;
        *)
            _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
            ;;
        esac
        shift
    done
}

checkAppExists() {
    _Application=$1
    _UserName=$2
    if [[ -z "${_Application}" ]]; then
        echo "[Error] No application was specified."
        exit 1
    fi

    if [ -f "/Applications/${_Application}" ] || [ -f "/Users/${_UserName}/Applications/${_Application}" ]; then
        return 1
    else
        return 0
    fi
}

closeApp() {
    _UserName=$1
    _Application=$2
    # Force close the app by the user name
    if [[ "${_arg_force}" == "true" ]] && [[ "${_runningAsRoot}" == "true" ]]; then
        if ! su "${_UserName}" -c "osascript -e 'tell application \"${_Application}\" to quit'" 2>/dev/null; then
            echo "[Warn] Failed to force close ${_Application} for user ${_UserName}."
        else
            echo "[Info] Successfully force closed ${_Application} for user ${_UserName}."
        fi
    elif [[ "${_arg_force}" == "true" ]] && [[ "${_runningAsRoot}" == "false" ]]; then
        if ! osascript -e "tell application \"${_Application}\" to quit" 2>/dev/null; then
            echo "[Warn] Failed to force close ${_Application} for user ${_UserName}."
        else
            echo "[Info] Successfully force closed ${_Application} for user ${_UserName}."
        fi
    fi
}

clearCache() {
    _UserName=$1

    if [[ -z "${_UserName}" ]]; then
        echo "[Warn] ${_UserName} is not a valid user name. Skipping."
        return
    fi

    # Check that the path /Users/"$_UserName"/ exists
    if [[ ! -d "/Users/$_UserName/Library" ]]; then
        echo "[Warn] User $_UserName does not exist. Skipping."
        return
    fi

    _browserFound="false"
    # Safari
    #   /Users/$_user/Library/Caches/com.apple.Safari/WebKitCache
    if [[ "${_arg_browser}" == *"Safari"* ]] || [[ "${_arg_browser}" == *"safari"* ]]; then
        _browserFound="true"
        # Check if the app exists
        if checkAppExists "Safari.app" "${_UserName}"; then
            # Check if the user is logged in
            # Force close Safari by the user name
            closeApp "$_UserName" "Safari"
            # Check if the cache directory exists
            if ls /Users/"$_UserName"/Library/Caches/com.apple.Safari/WebKitCache 2>/dev/null | head -n 1 | grep -q .; then
                # Clear the cache for Safari
                rm -rf /Users/"$_UserName"/Library/Caches/com.apple.Safari/WebKitCache 2>/dev/null
                echo "[Info] Cleared Safari cache for user $_UserName"
            else
                echo "[Warn] Safari cache directory does not exist. Skipping."
            fi
        else
            echo "[Warn] Safari.app is not installed. Skipping."
        fi
    fi

    # Chrome
    #   /Users/$_user/Library/Caches/Google/Chrome/*/Cache
    if [[ "${_arg_browser}" == *"Chrome"* ]] || [[ "${_arg_browser}" == *"chrome"* ]]; then
        _browserFound="true"
        # Check if the app exists
        if checkAppExists "Google Chrome.app" "${_UserName}"; then
            # Force close Chrome by the user name
            closeApp "$_UserName" "Google Chrome"
            # Check if the cache directories exists
            if ls /Users/"$_UserName"/Library/Caches/Google/Chrome/*/Cache 2>/dev/null | head -n 1 | grep -q .; then
                # Clear the cache for Chrome
                rm -rf /Users/"$_UserName"/Library/Caches/Google/Chrome/*/Cache 2>/dev/null
                echo "[Info] Cleared Chrome cache for user $_UserName"
            else
                echo "[Warn] Chrome cache directory does not exist. Skipping."
            fi
        else
            echo "[Warn] Google Chrome.app is not installed. Skipping."
        fi
    fi

    # Firefox
    #   /Users/$_user/Library/Caches/Firefox/Profiles/????????.*/cache2/*
    if [[ "${_arg_browser}" == *"Firefox"* ]] || [[ "${_arg_browser}" == *"firefox"* ]]; then
        _browserFound="true"
        # Check if the app exists
        if checkAppExists "Firefox.app" "${_UserName}"; then
            # Force close Firefox by the user name
            closeApp "$_UserName" "Firefox"
            # Check if the cache directories exists
            if ls /Users/"$_UserName"/Library/Caches/Firefox/Profiles/????????.*/cache2/* 2>/dev/null | head -n 1 | grep -q .; then
                # Clear the cache for Firefox
                rm -rf /Users/"$_UserName"/Library/Caches/Firefox/Profiles/????????.*/cache2/* 2>/dev/null
                echo "[Info] Cleared Firefox cache for user $_UserName"
            else
                echo "[Warn] Firefox cache directory does not exist. Skipping."
            fi
        else
            echo "[Warn] Firefox.app is not installed. Skipping."
        fi
    fi

    # Edge
    #   /Users/$_user/Library/Caches/Microsoft Edge/*/Cache
    if [[ "${_arg_browser}" == *"Edge"* ]] || [[ "${_arg_browser}" == *"edge"* ]]; then
        _browserFound="true"
        # Check if the app exists
        if checkAppExists "Microsoft Edge.app" "${_UserName}"; then
            # Force close Edge by the user name
            closeApp "$_UserName" "Microsoft Edge"
            # Check if the cache directories exists
            if ls /Users/"$_UserName"/Library/Caches/Microsoft\ Edge/*/Cache 2>/dev/null | head -n 1 | grep -q .; then
                # Clear the cache for Edge
                rm -rf /Users/"$_UserName"/Library/Caches/Microsoft\ Edge/*/Cache 2>/dev/null
                echo "[Info] Cleared Edge cache for user $_UserName"
            else
                echo "[Warn] Edge cache directory does not exist. Skipping."
            fi
        else
            echo "[Warn] Microsoft Edge.app is not installed. Skipping."
        fi
    fi

    if [[ "$_browserFound" == "false" ]]; then
        echo "[Error] At least one browser must be specified. Please specify one of the following: Chrome, Firefox, Edge, Safari."
        exit 1
    fi
}

parse_commandline "$@"

# If script variable is used override commandline arguments
if [[ -n $userNames ]]; then
    # Split userNames into an array
    _arg_userNames=$userNames
fi

if [[ -z $chrome ]] && [[ -z $firefox ]] && [[ -z $edge ]] && [[ -z $safari ]] && [[ -z $_arg_browser ]]; then
    echo "[Error] At least one browser must be specified. Please specify one of the following: Chrome, Firefox, Edge, Safari."
    exit 1
fi

# Append browser names to _arg_browser as we check if the name exists in _arg_browser later on
if [[ -n $chrome ]] && [[ "${chrome}" == "true" ]]; then
    _arg_browser="$_arg_browser,chrome"
fi
if [[ -n $firefox ]] && [[ "${firefox}" == "true" ]]; then
    _arg_browser="$_arg_browser,firefox"
fi
if [[ -n $edge ]] && [[ "${edge}" == "true" ]]; then
    _arg_browser="$_arg_browser,edge"
fi
if [[ -n $safari ]] && [[ "${safari}" == "true" ]]; then
    _arg_browser="$_arg_browser,safari"
fi

if [[ -n $force ]]; then
    if [[ "${force}" == "true" ]]; then
        _arg_force="true"
    else
        _arg_force="false"
    fi
fi

# Check if the user is running this script as root
_runningAsRoot="false"
if [[ $EUID -eq 0 ]]; then
    _runningAsRoot="true"
fi

_Users=()
if [[ -z "${_arg_userNames}" ]] && [[ $_runningAsRoot == "true" ]]; then
    # Get a list of all user names that can login
    _userNames=$(dscl . -list /Users UniqueID | awk '$2 > 499 {print $1}')
    # Loop through each user name
    for _userName in $_userNames; do
        # Trim whitespace from the user name
        _userName="${_userName##*( )}" # Remove leading whitespace
        _userName="${_userName%%*( )}" # Remove trailing whitespace
        _Users+=("$_userName")
    done
else
    IFS=',' read -r -a _userNames <<<"$_arg_userNames"
    for _userName in "${_userNames[@]}"; do
        # Trim whitespace from the user name
        _userName="${_userName##*( )}" # Remove leading whitespace
        _userName="${_userName%%*( )}" # Remove trailing whitespace
        _Users+=("$_userName")
    done
fi

if [[ $_runningAsRoot == "true" ]]; then
    # Check if the user is in the list of users to clear cache for
    for _userName in "${_Users[@]}"; do
        _user=$(echo "$_userName" | awk '{$1=$1};1')
        if dscl . read "/Users/$_user" 1>/dev/null 2>&1; then
            clearCache "$_user"
            echo ""
        else
            echo "[Warn] ${_user} is not a valid user name. Skipping."
        fi
    done
else
    if [[ "$(whoami)" == "${_arg_userNames}" ]] || [[ -z "${_arg_userNames}" ]]; then
        clearCache "$(whoami)"
    else
        echo "[Error] The script must be run as system/root to clear the cache for multiple users."
        exit 1
    fi
fi

 

Save time with over 300+ scripts from the NinjaOne Dojo.

Get access today.

Detailed Breakdown

This Bash script is highly versatile and supports parameterized execution. Below is a detailed explanation of its functionality:

Input Parameters

  • –UserName or -u: Specifies one or multiple users (e.g., User1,User2) for whom the cache will be cleared. If not provided, the script defaults to the current user.
  • –Browser or -b: Indicates which browser(s) to target. Valid options include Chrome, Firefox, Safari, and Edge. Multiple browsers can be specified (e.g., Chrome,Firefox).
  • –Force or -f: Forcefully closes the specified browsers before clearing their cache.

Core Functions

  1. Help and Error Handling
    The print_help function provides usage guidelines, while the die function handles invalid inputs or errors gracefully by displaying error messages.
  2. Parsing Parameters
    The parse_commandline function processes user inputs to determine which browsers and users to target.
  3. Application Validation
    The checkAppExists function checks for the existence of the target browsers in both system-wide and user-specific application directories.
  4. Force Closing Browsers
    The closeApp function uses osascript to close browser applications for specified users, ensuring no conflicts during cache clearance.
  5. Cache Clearance
    The clearCache function identifies cache directories for each browser and user, removes the relevant files, and logs actions to the console. For example:
  6. Chrome: Clears /Users/{username}/Library/Caches/Google/Chrome/*/Cache.
  7. Safari: Removes /Users/{username}/Library/Caches/com.apple.Safari/WebKitCache.

Execution

The script ensures that it runs with appropriate permissions (root access when clearing caches for multiple users) and defaults to the current user if no username is specified.

Real-World Use Cases

Scenario

An IT administrator at a mid-sized company manages a fleet of macOS devices. Employees use multiple browsers, often leading to performance issues due to outdated or bloated cache files.

Frequently Asked Questions

  1. Do I need administrative privileges?
    Yes, root access is required to clear caches for multiple users.
  2. Can I clear cache for a single browser only?
    Absolutely. Use the –Browser parameter to specify the browser(s) you want to target.
  3. What happens if a browser is open during execution?
    If the –Force parameter is used, the script will attempt to close the browser before clearing the cache.
  4. Can this script be scheduled?
    Yes, it can be run via cron or any task scheduler on macOS for automated cache management.

Broader Implications

Clearing browser caches regularly enhances system performance, reduces storage bloat, and minimizes potential security risks, such as retaining sensitive data in cache files. For organizations, this translates into reduced support tickets and better user satisfaction.

Best Practices

  • Run as Root: Always execute the script with administrative privileges for multi-user operations.
  • Test in a Safe Environment: Validate the script in a test environment before deploying it organization-wide.
  • Schedule Regular Maintenance: Use task schedulers to automate the script for consistent cache management.
  • Document Usage: Maintain logs of cache-clearing activities for auditing and troubleshooting.

Final Thoughts

This script showcases how automation can alleviate repetitive tasks for IT administrators. While tools like NinjaOne offer comprehensive IT management solutions, scripts like this can complement broader strategies by tackling specific challenges. NinjaOne’s robust capabilities, including automation, monitoring, and management, make it an invaluable ally for IT professionals aiming for efficiency and reliability.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).