Full Guide: How to Use a Linux Script to Check for File or Folder Existence

Ensuring the integrity and presence of critical files and directories is paramount in IT management. Whether you’re an IT professional or a managed service provider (MSP), keeping track of essential system files or specific application directories can help maintain system stability, security, and compliance. This is where automation scripts come into play, particularly one that can alert you if a specified file or folder is found within a directory or subdirectory.

Background

The script provided offers a robust solution for searching and alerting based on file or folder existence within a specified path. This kind of automation is crucial in various scenarios, such as verifying deployment success, monitoring unauthorized changes, or ensuring critical configurations are in place. For IT professionals and MSPs, leveraging such scripts can enhance operational efficiency and reduce manual monitoring efforts.

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
}

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

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

# 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}m" 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}m" 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}m" 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
    # Search in path only
    echo "[Info] Searching in path only"
    # Search in path only
    # Use timeout to prevent the find command from running indefinitely
    foundPath=$(timeout "${timeout}m" 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
    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 "[Info] ${foundPath} does not exist"
    fi
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 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

Let’s delve into the script to understand its workings, parameters, and functionality:

Parameters and Options

The script accepts several parameters to customize the search operation:

  • –path “/opt/NinjaRMM/programdata”: Specifies the base path to search for files or folders. This parameter is required.
  • –name “ninjarmm-cli”: Defines the name of the file or folder to search for. This is also required and supports case sensitivity and wildcards.
  • –type “Files Or Folders”: Determines whether to search for files, folders, or both. Required parameter with options:
  • Files Only
  • Folders Only
  • Files Or Folders
  • –timeout 10: An optional parameter specifying the time (in minutes) to wait for the search to complete before timing out, defaulting to 30 minutes.
  • –customfield “myCustomField”: An optional parameter to save the search results to a custom field.

Script Execution Flow

1. Initialization and Parsing Arguments: The script begins by defining utility functions (die and begins_with_short_option) and initializing argument variables. The parse_commandline function processes the provided arguments, validating and assigning them to respective variables.

2. SetCustomField Function: This function sets a custom field with the search results if the ninjarmm-cli tool is available and executable. It checks for various conditions, such as the existence of the tool and the custom field, and handles the value length constraints.

3. Main Logic:

  • The script validates the required path parameter and ensures the specified directory exists.
  • It checks if the timeout value is a number within the acceptable range (1 to 120 minutes).
  • Depending on the specified type (Files Only, Folders Only, Files Or Folders), it performs the search using the find command with a timeout to prevent indefinite execution.
  • The search results are handled appropriately, alerting if the file or folder is found and saving the results to a custom field if specified.

Potential Use Cases

  1. Deployment Verification: Ensuring that critical files are present post-deployment to confirm successful application installation.
  2. Security Monitoring: Detecting unauthorized file or directory additions, which could indicate a security breach or policy violation.
  3. Compliance Audits: Verifying the presence of necessary configuration files or logs required for compliance with industry standards.

Hypothetical Case Study

Imagine an MSP managing multiple client environments. By deploying this script across client systems, the MSP can automate the verification process of important files, such as antivirus definitions or system configurations, ensuring they are up-to-date and compliant with security policies. If any discrepancies are found, the script alerts the MSP, enabling quick remediation.

Comparisons

Traditional methods of checking file existence might involve manual commands or basic scripts lacking robust error handling and customization options. The provided script stands out by offering comprehensive parameterization, timeout management, and integration with custom fields for result storage. This level of automation and flexibility significantly enhances operational efficiency.

FAQs

Q: Can this script search for multiple files or folders at once?

A: No, the script is designed to search for a single specified file or folder. Multiple searches would require multiple script executions.

Q: How does the script handle large directories?

A: The script uses the find command with a timeout to prevent long-running searches. This ensures it doesn’t hang indefinitely in large directories.

Q: What happens if the ninjarmm-cli tool is not available?

A: The script logs a warning and continues its operation. The custom field functionality would be skipped if the tool is not executable.

Implications

The ability to automate file and folder existence checks has significant implications for IT security and management. Automated alerts help in quickly identifying unauthorized changes, potential breaches, and compliance issues. This proactive approach enhances overall system security and reliability.

Recommendations

  • Set Appropriate Timeouts: Ensure the timeout value is realistic for the directory size to prevent unnecessary script terminations.
  • Regularly Update Search Criteria: Adapt the search parameters based on evolving requirements, such as new critical files or directories.
  • Integrate with Monitoring Systems: Use the custom field functionality to integrate with broader monitoring and alerting systems, providing a unified view of system health and compliance.

Final Thoughts

Automation scripts like the one discussed are invaluable tools for IT professionals and MSPs. They provide a reliable, efficient way to ensure critical files and directories are present and correct. By integrating this script into your IT management practices, you can enhance security, compliance, and operational efficiency. NinjaOne offers a suite of tools that can complement such scripts, providing comprehensive IT management solutions tailored to your needs.

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

Watch Demo×
×

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