How to Automate File and Folder Existence Checks in macOS

In the IT world, automating repetitive tasks can save time and reduce errors. One such task is checking the existence of specific files or folders across multiple directories. Whether it’s for compliance, system monitoring, or troubleshooting, having an automated way to verify file presence can be invaluable for IT professionals and Managed Service Providers (MSPs). This blog post explores a Bash script designed to streamline this process, ensuring efficiency and reliability in file management.

Background

This script is particularly useful for IT professionals who need to verify the existence of critical files or folders regularly. It provides an automated solution to search through directories, ensuring that important files are present or identifying when they are missing. This capability is crucial in various scenarios, such as validating backup locations, ensuring the presence of configuration files, or confirming the deployment of critical applications.

The Script

#!/usr/bin/env bash

# Description: Alert if a specified file or folder is found in a directory or subdirectory you specify.
#
# Release Notes: Initial Release
# 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).
#
# Below are all the (case sensitive) valid parameters for this script.
# Only the path to search and name of file or folder are required!
#
# Parameter: --path "/opt/NinjaRMM/programdata"
#   Required
#   Base path to search for files or folders.
#
# Parameter: --name "ninjarmm-cli"
#   Required
#   Name of the file or folder to search for.
#   Notes:
#       If the name is not provided, the script will search for the path only.
#       This is case sensitive and accepts wildcards.
#
# Parameter: --type "Files Or Folders"
#   Required
#   Search for files or folders.
#
# Parameter: --type "Files Only"
#   Required
#   Searches for files only.
#
# Parameter: --type "Folders Only"
#   Required
#   Searches for folder only.
#
# Parameter: --timeout 10
#   Optional and defaults to 30 minutes
#   Time in minutes to wait for the search to complete before timing out.
#
# Parameter: --customfield "myCustomField"
#   Optional
#   Custom Field to save the search results to.

die() {
    local _ret="${2:-1}"
    test "${_PRINT_HELP:-no}" = yes && print_help >&2
    echo "$1" >&2
    exit "${_ret}"
}

begins_with_short_option() {
    local first_option all_short_options='h'
    first_option="${1:0:1}"
    test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

# Initize arguments
_arg_path=
_arg_name=
_arg_type=
_arg_timeout=30
_arg_customfield=

print_help() {
    printf '%s\n' "Check existence of a file or folder"
    printf 'Usage: %s [--path <arg>] [--name <arg>] [--type <"Files Only"|"Folders Only"|"Files Or Folders">] [--timeout <30>] [--customfield <arg>] [-h|--help]\n' "$0"
    printf '\t%s\n' "-h, --help: Prints help"
}

parse_commandline() {
    while test $# -gt 0; do
        _key="$1"
        case "$_key" in
        --path)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_path="$2"
            shift
            ;;
        --path=*)
            _arg_path="${_key##--path=}"
            ;;
        --name)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_name="$2"
            shift
            ;;
        --name=*)
            _arg_name="${_key##--name=}"
            ;;
        --type)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_type="$2"
            shift
            ;;
        --type=*)
            _arg_type="${_key##--type=}"
            ;;
        --timeout)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_timeout="$2"
            shift
            ;;
        --timeout=*)
            _arg_timeout="${_key##--timeout=}"
            ;;
        --customfield)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_customfield="$2"
            shift
            ;;
        --customfield=*)
            _arg_customfield="${_key##--customfield=}"
            ;;
        -h | --help)
            print_help
            exit 0
            ;;
        -h*)
            print_help
            exit 0
            ;;
        *)
            _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
            ;;
        esac
        shift
    done
}

parse_commandline "$@"

function SetCustomField() {
    customfieldName=$1
    customfieldValue=$2
    if [ -f "${NINJA_DATA_PATH}/ninjarmm-cli" ]; then
        if [ -x "${NINJA_DATA_PATH}/ninjarmm-cli" ]; then
            if "$NINJA_DATA_PATH"/ninjarmm-cli get "$customfieldName" >/dev/null; then
                # check if the value is greater than 10000 characters
                if [ ${#customfieldValue} -gt 10000 ]; then
                    echo "[Warn] Custom field value is greater than 10000 characters"
                fi
                if ! echo "${customfieldValue::10000}" | "$NINJA_DATA_PATH"/ninjarmm-cli set --stdin "$customfieldName"; then
                    echo "[Warn] Failed to set custom field"
                else
                    echo "[Info] Custom field value set successfully"
                fi
            else
                echo "[Warn] Custom Field ($customfieldName) does not exist or agent does not have permission to access it"
            fi
        else
            echo "[Warn] ninjarmm-cli is not executable"
        fi
    else
        echo "[Warn] ninjarmm-cli does not exist"
    fi
}

if [ ! "$(command -v timeout)" ]; then
    notimeout=true
    # If the timeout command does not exist, create a function to mimic the timeout command
    function timeout() { perl -e 'alarm shift; exec @ARGV' "$@"; }
fi

parentSearchPath=$_arg_path
leafSearchName=$_arg_name
searchType=$_arg_type
timeout=$_arg_timeout
customField=$_arg_customfield

# Get values from Script Variables
if [[ -n "${pathToSearch}" ]]; then
    parentSearchPath="${pathToSearch}"
fi
if [[ -n "${nameOfFileOrFolder}" ]]; then
    leafSearchName="${nameOfFileOrFolder}"
fi
if [[ -n "${filesOrFolders}" && "${filesOrFolders}" != "null" ]]; then
    searchType="${filesOrFolders}"
fi
if [[ -n "${searchTimeout}" && "${searchTimeout}" != "null" ]]; then
    timeout="${searchTimeout}"
fi
if [[ -n "${customFieldName}" && "${customFieldName}" != "null" ]]; then
    customField="${customFieldName}"
fi

# Check if parentSearchPath is a link and replace it with the resolved path
if [ -L "${parentSearchPath}" ]; then
    echo "[Info] Path to Search is a link: ${parentSearchPath} -> $(readlink -f "${parentSearchPath}")"
    echo "[Info] Will use the resolved path to search"
    parentSearchPath=$(readlink -f "${parentSearchPath}")
fi

if [[ -z "${parentSearchPath}" ]]; then
    echo "[Error] Path to Search is empty"
    exit 1
fi

# Check if path exists
if [ -e "${parentSearchPath}" ]; then
    echo "[Info] Path ${parentSearchPath} exists"
else
    echo "[Error] Path to Search ${parentSearchPath} does not exist or is an invalid path"
    exit 1
fi

# Check if timeout is a number
if ! [[ "${timeout}" =~ ^[0-9]+$ ]]; then
    echo "[Error] Timeout is not a number"
    exit 1
fi
# Check if timeout is not in the range of 1 to 120
if [[ "${timeout}" -lt 1 || "${timeout}" -gt 120 ]]; then
    echo "[Error] Timeout is not in the range of 1 to 120"
    exit 1
fi

# Check if search type is valid

if $notimeout; then
    # If the timeout command does not exist, convert the timeout to minutes
    timeout=$((timeout * 60))
else
    # If the timeout command does exist, add m to the end of the string
    timeout="${timeout}m"
fi

if [[ $OSTYPE == 'darwin'* ]]; then
    if ! plutil -lint /Library/Preferences/com.apple.TimeMachine.plist >/dev/null; then
        echo "This script requires ninjarmm-macagent to have Full Disk Access."
        echo "Add ninjarmm-macagent to the Full Disk Access list in System Preferences > Security & Privacy, quit the app, and re-run this script."
        exit 1
    fi
fi

# Search for files or folders
if [[ -n "${leafSearchName}" && "${leafSearchName}" != "null" ]]; then
    if [[ "${searchType}" == *"Files"* && "${searchType}" == *"Only"* ]]; then
        echo "[Info] Searching for files only"
        # Search for files only
        # Use timeout to prevent the find command from running indefinitely
        foundPath=$(timeout "${timeout}" find "$parentSearchPath" -type f -name "$leafSearchName" 2>/dev/null)
        exitcode=$?
        if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
            if [[ -n $foundPath ]]; then
                echo "[Alert] File Found"
            fi
        fi
    elif [[ "${searchType}" == *"Folders"* && "${searchType}" == *"Only"* ]]; then
        echo "[Info] Searching for folders only"
        # Search for folders only
        # Use timeout to prevent the find command from running indefinitely
        foundPath=$(timeout "${timeout}" find "$parentSearchPath" -type d -name "$leafSearchName" 2>/dev/null)
        exitcode=$?
        if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
            if [[ -n $foundPath ]]; then
                echo "[Alert] File Found"
            fi
        fi
    elif [[ "${searchType}" == *"Files"* && "${searchType}" == *"Folders"* ]]; then
        echo "[Info] Searching for files or folders"
        # Search for files or folders
        # Use timeout to prevent the find command from running indefinitely
        foundPath=$(timeout "${timeout}" find "$parentSearchPath" -name "$leafSearchName" 2>/dev/null)
        exitcode=$?
        if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
            if [[ -n $foundPath ]]; then
                echo "[Alert] File Found"
            fi
        fi
    else
        echo "[Error] Invalid search type"
        echo "Valid search types: Files Only, Folders Only, Files Or Folders"
        exit 1
    fi
elif [[ -z "${leafSearchName}" ]]; then
    echo "[Info] Searching in path only"
    # Search in path only
    # Use timeout to prevent the find command from running indefinitely
    foundPath=$(timeout "${timeout}" find "$parentSearchPath")
    exitcode=$?
    if [[ $exitcode -eq 0 || $exitcode -eq 124 ]]; then
        if [[ -n $foundPath ]]; then
            echo "[Alert] File Found"
        fi
    fi
fi

# Check exit code
if [[ -n $foundPath ]]; then
    # Split the string into an array
    IFS=$'\n' read -rd '' -a foundPathArray <<<"${foundPath}"
    # Print each element of the array
    for element in "${foundPathArray[@]}"; do
        echo "[Alert] ${element} exists"
    done
elif [[ -z $foundPath ]]; then
    echo "[Warn] Could not find a file or folder"
    exit 1
else
    # If the find command fails to find the file or folder

    # Figure out the grammer for the search type
    if [[ "${searchType}" == *"Only"* ]]; then
        if [[ "${searchType}" == *"Files"* ]]; then
            searchTypeInfo="file"
        elif [[ "${searchType}" == *"Folders"* ]]; then
            searchTypeInfo="folder"
        fi
    elif [[ "${searchType}" == *"Files"* && "${searchType}" == *"Folders"* ]]; then
        searchTypeInfo="file or folder"
    fi
    echo "[Info] Could not find a ${searchTypeInfo} in the path ${parentSearchPath} with the name containing: ${leafSearchName}"
fi

# If foundPath contains "Alarm clock:" then the command timed out
if [[ "${foundPath}" == *"Alarm clock:"* ]]; then
    echo "[Alert] Timed out searching for file or folder"
    # Remove "Alarm clock: *" from the string
    foundPath=${foundPath/Alarm clock: [0-9]*//}
fi

# If command times out
if [[ $exitcode -ge 124 && $exitcode -le 127 || $exitcode -eq 137 ]]; then
    echo "[Alert] Timed out searching for file or folder"
    echo "timeout exit code: $exitcode"
    echo "  124  if COMMAND times out, and --preserve-status is not specified"
    echo "  125  if the timeout command itself fails"
    echo "  126  if COMMAND is found but cannot be invoked"
    echo "  127  if COMMAND cannot be found"
    echo "  137  if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)"
    echo "find command result: $foundPath"
    exit 1
fi

# Save to custom field
if [[ -n "${customField}" && "${customField}" != "null" ]]; then
    SetCustomField "${customField}" "${foundPath}"
fi

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script operates by taking several parameters to customize the search process. Here’s a detailed breakdown of its functionality:

1. Parameters and Initialization:

  • –path: Specifies the base directory to search within.
  • –name: Defines the name of the file or folder to look for, supporting wildcards.
  • –type: Determines whether to search for files, folders, or both.
  • –timeout: Sets the maximum time for the search operation, defaulting to 30 minutes.
  • –customfield: Allows saving the search result to a custom field.

2. Argument Parsing: The script parses the command-line arguments to initialize the search parameters. If any required parameter is missing, it provides an error message and exits.

3. Search Execution:

  • The script resolves any symbolic links in the search path.
  • It verifies that the specified path exists and is valid.
  • It ensures the timeout is within the acceptable range (1 to 120 minutes).

4. File or Folder Search: Depending on the specified type (files, folders, or both), the script uses the find command with a timeout to locate the desired items. If found, it alerts the user and optionally saves the result to a custom field.

5. Error Handling and Reporting: The script includes comprehensive error handling, ensuring that issues like invalid paths, incorrect timeout values, or non-existent files/folders are reported clearly to the user.

Potential Use Cases

Case Study: IT Compliance Verification

An IT professional is responsible for ensuring that critical security configuration files are present on all servers. Using this script, they can automate the verification process:

1. Setup:

  • –path: /etc/security
  • –name: security.conf
  • –type: Files Only
  • –timeout: 10

2. Execution: The script searches the specified path for the security.conf file within the set timeout period. If found, it logs an alert; if not, it notifies the IT professional, enabling quick remediation.

Comparisons

Compared to manual verification or using basic shell commands, this script offers several advantages:

  • Automation: Reduces the need for manual checks.
  • Timeout Management: Prevents prolonged searches by enforcing a timeout.
  • Custom Reporting: Allows results to be saved to custom fields for further processing or compliance reporting.

Other methods, like using ls or test commands in Bash, lack these advanced features, making this script a more robust and efficient solution.

FAQs

  1. What happens if the script times out?
    The script reports a timeout and exits with an appropriate error code, ensuring the user is aware that the search was incomplete.
  2. Can I search for multiple file types simultaneously?
    No, the script currently supports searching for files or folders based on a single name pattern at a time.
  3. How do I handle symbolic links in the search path?
    The script automatically resolves symbolic links, ensuring the search is conducted in the correct directory.

Implications

Using this script can significantly enhance IT security by ensuring critical files and folders are present. Automated verification helps maintain compliance with security policies and reduces the risk of missing important files, which could lead to system vulnerabilities or failures.

Recommendations

  • Regular Audits: Schedule the script to run regularly to maintain up-to-date verification of critical files.
  • Custom Field Utilization: Leverage the custom field option to track and report search results systematically.
  • Timeout Settings: Adjust the timeout parameter based on the expected size of the directory and system performance to avoid unnecessary delays.

Final Thoughts

This Bash script is a powerful tool for IT professionals, providing an automated and reliable method to verify the existence of files and folders. By integrating this script into routine checks, MSPs can ensure higher efficiency and security in their operations. Tools like NinjaOne can further enhance this process by offering comprehensive IT management solutions, making it easier to deploy, monitor, and manage scripts across multiple systems.

Embracing automation in file management not only saves time but also enhances accuracy, ensuring that critical files are always where they need to be.

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

How to Monitor Log Files on macOS with a Custom Bash Script

How to Monitor Log Files and Detect Specific Text on Linux Using a Bash Script

How to Use PowerShell to Monitor Text Files and Trigger Alerts for IT Professionals

How to Automate Microsoft Safety Scanner Using a PowerShell Script

Comprehensive Guide to Using PowerShell for Efficient Event Log Searches

How to Use PowerShell to Detect Open and Established Ports in Windows

×

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).