How to Enable or Disable File Extensions in macOS with Shell Scripting

Managing system settings at scale is a critical responsibility for IT professionals and managed service providers (MSPs). macOS, while user-friendly on the surface, can pose configuration challenges when trying to enforce uniform settings across multiple users or systems. One such setting is the visibility of file extensions, which can be essential for IT diagnostics, file-type integrity, and user education. This post explores how to enable or disable file extensions in macOS with Shell scripting for all users via command-line automation.

Background

File extensions are vital for distinguishing file types, especially when file icons or default applications are ambiguous. While users can toggle this setting manually via Finder preferences, enterprise environments demand automation, especially when managing hundreds of machines. MSPs and sysadmins often need to enforce visibility to prevent user errors, enable effective file management, or comply with policy guidelines. The script discussed here enables or disables the “Show all file extensions” feature across all user accounts—automatically, reliably, and with minimal intervention.

This tool is particularly valuable when paired with remote management solutions like NinjaOne, where automation can reduce time-to-resolution, enforce security postures, and eliminate inconsistencies across deployments.

The Script

#!/usr/bin/env bash

# Description: Enable or disable the visibility of File Extensions for all users (must be ran as 'System').
# 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).
#
# Release Notes: Initial Release
#
# Usage: [--action <Arg>] [--restartFinder] [--help|-h]
# <> are required
# [] are optional
#
# Example: Set-ExtensionVisibility.sh --action Enable
#   Enabling 'Show hidden files and folders' for all users.
#
# Example: Set-ExtensionVisibility.sh --action Enable --restartFinder
#   Enabling 'Show hidden files and folders' for all users.
#   Restarting Finder.
#
# Preset Parameter: --action "Enable"
#   Specify whether you would like to disable or enable the viewing of hidden files or folders. Valid actions are 'Enable' or 'Disable'.
#
# Preset Parameter: --restartFinder
#   You may need to restart Finder.app for the script to take effect immediately. Use this switch to do so upon completion.
#
# Preset Parameter: --help
#   Displays the help menu.

# Functions
# Print an error message and exit with a specific status code
die() {
    local _ret="${2:-1}"
    test "${_PRINT_HELP:-no}" = yes && print_help >&2
    echo "$1" >&2
    exit "${_ret}"
}

# Print the help message
print_help() {
    printf '\n\n%s\n\n' 'Usage: [-a|--action <Arg>] [-r|--restartFinder] [-h|--help]'
    printf '%s\n' 'Preset Parameter: --action "Enable"'
    printf '%s\n' 'Preset Parameter: --action "Disable"'
    printf '\t%s\n' "Specify whether you would like to disable or enable the viewing of hidden files or folders. Valid actions are 'Enable' or 'Disable'."
    printf '%s\n' 'Preset Parameter: --restartFinder'
    printf '\t%s\n' "You may need to restart Finder.app for the script to take effect immediately. Use this switch to do so upon completion."
    printf '%s\n' 'Preset Parameter: --help'
    printf '\t%s\n' "Displays the help menu."
}

# Parse the command-line arguments
parse_commandline() {
    while test $# -gt 0; do
        _key="$1"
        case "$_key" in
        -a | --action)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_action="$2"
            shift
            ;;
        --action=*)
            _arg_action="${_key##--action=}"
            ;;
        -a*)
            _arg_action="${_key##-a}"
            ;;
        --restartFinder | -r)
            _arg_restartFinder="true"
            ;;
        --help | -h)
            _PRINT_HELP=yes die "" 0
            ;;
        *)
            _PRINT_HELP=yes die "[Error] Got an unexpected argument '$1'" 1
            ;;
        esac
        shift
    done
}

setExtensionVisibility() {
    user=$1
    if [[ "${_arg_action}" == "Enable" ]]; then
        if [[ $(sudo -u "$user" /usr/bin/defaults read NSGlobalDomain AppleShowAllExtensions 2>&1) == "1" ]]; then
            # If the visibility of File Extensions is already enabled, display a message indicating that it is already enabled
            echo "[Info] 'Show File Extensions' is already enabled for user '$user'."
            # If the restartFinder flag is "on", restart Finder as requested and handle any errors
            if [[ $_arg_restartFinder == "on" ]]; then
                restartFinder "$user"
            fi
        else
            # Enable the visibility of File Extensions for the user
            echo "[Info] Enabling 'Show File Extensions' for user '$user'."
            if sudo -u "$user" /usr/bin/defaults write NSGlobalDomain AppleShowAllExtensions -bool true 2>&1; then
                # If the restartFinder flag is "on", restart Finder as requested and handle any errors
                if [[ $_arg_restartFinder == "on" ]]; then
                    restartFinder "$user"
                fi
                echo "[Info] Successfully set 'Show File Extensions' to 'Enable' for user '$user'."
            else
                echo "[Error] Failed to set 'Show File Extensions' to 'Enable' for user '$user'."
            fi
        fi
    else
        if [[ $(sudo -u "$user" /usr/bin/defaults read NSGlobalDomain AppleShowAllExtensions 2>&1) == "1" ]]; then
            # Disable the visibility of File Extensions for the user
            echo "[Info] Disabling 'Show File Extensions' for user '$user'."
            if sudo -u "$user" /usr/bin/defaults write NSGlobalDomain AppleShowAllExtensions -bool false 2>&1; then
                # If the restartFinder flag is "on", restart Finder as requested and handle any errors
                if [[ $_arg_restartFinder == "on" ]]; then
                    restartFinder "$user"
                fi
                echo "[Info] Successfully set 'Show File Extensions' to 'Disable' for user '$user'."
            else
                echo "[Error] Failed to set 'Show File Extensions' to 'Disable' for user '$user'."
            fi
        else
            # If the visibility of File Extensions is already disabled, display a message indicating that it is already disabled
            echo "[Info] 'Show File Extensions' is already disabled for user '$user'."
            # If the restartFinder flag is "on", restart Finder as requested and handle any errors
            if [[ $_arg_restartFinder == "on" ]]; then
                restartFinder "$user"
            fi
        fi
    fi
}

restartFinder() {
    user=$1
    # Restart Finder for the user
    echo "[Info] Restarting Finder as requested for user '$user'."
    # Check if Finder is running for the user before restarting it
    if pgrep -u "$user" Finder 1>/dev/null 2>&1; then
        # Finder is running for the user, restart Finder
        echo "[Info] Finder is running for user '$user'."
        if pkill -u "$user" Finder 2>&1; then
            # Finder was successfully restarted
            echo "[Info] Restarted Finder for user '$user'."
        else
            # Finder failed to restart
            echo "[Warn] Failed to restart Finder for user '$user'."
        fi
    else
        # Finder is not running for the user
        echo "[Info] Finder is not running for user '$user'."
    fi
}

parse_commandline "$@"

# If script form variables are used, replace the command-line parameters with their value.
if [[ -n "${action}" ]]; then
    _arg_action="$action"
fi

if [[ -n $restartFinder && $restartFinder == "true" ]]; then
    _arg_restartFinder="on"
fi

# If $action has a value, trim any leading or trailing whitespace
if [[ -n "${_arg_action}" ]]; then
    _arg_action="$(echo -e "${_arg_action}" | xargs)"
fi

# If $action is empty or null after trimming, display an error message indicating that an action must be specified
if [[ -z "${_arg_action}" ]]; then
    die "[Error] You must specify an action (Enable or Disable)." 1
fi

# Check if the action is valid
if [[ "${_arg_action}" != "Enable" && "${_arg_action}" != "Disable" ]]; then
    die "[Error] Invalid action '${_arg_action}'. Please specify either 'Enable' or 'Disable'." 1
fi

if [[ $EUID -eq 0 ]]; then
    # Get all users with UID >= 500
    user_list=$(dscl . -list /Users UniqueID | awk '$2 > 499 {print $1}')

    # Set the visibility of File Extensions for all users
    for user in $user_list; do
        setExtensionVisibility "$user"
    done
else
    die "[Error] This script must be run as system or root." 1
fi

 

Detailed Breakdown

The shell script is designed to be executed as root or by the system user to ensure it has the necessary privileges. It offers the following functionality:

  • Toggle file extension visibility (Enable or Disable)
  • Restart Finder optionally to apply changes instantly
  • Support for all local users (UID ≥ 500)
  • CLI help menu for ease of use

Argument Parsing

The script begins with a function to parse command-line arguments such as:

  • –action <Enable|Disable>: Required to define the desired visibility state.
  • –restartFinder: Optional flag to restart Finder for the changes to take effect immediately.
  • –help: Displays usage instructions.

Main Logic

  1. Argument Validation
    If –action is missing or invalid, the script will exit with an error, prompting the user with proper usage instructions.
  2. User Enumeration
    Using dscl, the script retrieves all local users with UID ≥ 500—typically excluding system accounts.
  3. Per-user Configuration
    For each user:

    • It checks the current state of AppleShowAllExtensions using the defaults command.

Depending on the –action, it either enables or disables this setting using:
bash
CopyEdit
sudo -u “$user” /usr/bin/defaults write NSGlobalDomain AppleShowAllExtensions -bool true|false

  • If –restartFinder is set, Finder is gracefully restarted for the user to apply the change.

Potential Use Cases

Case Study: University IT Department

A university IT team needs to ensure all students working in programming labs can see file extensions to avoid misidentifying file types (e.g., .js vs .txt). Using this script, the admin schedules a task via NinjaOne to run weekly across all lab Macs. The script enforces visibility, reduces user confusion, and prevents common helpdesk tickets related to file mismanagement.

Comparisons

Manual Configuration

Users can manually change this setting via Finder > Preferences > Advanced > “Show all filename extensions.” This approach is not scalable and cannot guarantee consistency across multiple accounts or devices.

Configuration Profiles (MDM)

Apple’s MDM framework offers some Finder customizations, but visibility of file extensions is not universally exposed as a configurable payload across all versions. Moreover, shell scripting offers flexibility without needing a full MDM infrastructure.

Custom Login Scripts

Admin-created login scripts can change preferences per user, but they require session-based execution. This script works independently of login state, offering greater flexibility for offline or maintenance-window execution.

FAQs

Q: Does this script affect iCloud or network users?

A: No, it targets local users with UID ≥ 500 only.

Q: Will users notice changes immediately?

A: Only if –restartFinder is used. Otherwise, changes take effect the next time Finder is launched.

Q: Can I run this from a NinjaOne script policy?

A: Yes, as long as it’s executed with system/root permissions.

Q: What if a user resets the preference?

A: You can schedule this script to run at regular intervals or enforce it during login via NinjaOne.

Implications

Security and Operational Consistency

  • File Spoofing Prevention: Hidden extensions can lead to dangerous file types being disguised. Enforcing visibility helps prevent this.
  • User Training: Consistent environments aid in onboarding and support.
  • Policy Compliance: Organizations with strict data handling rules benefit from standardized file presentation.

Recommendations

  • Always run the script as root.
  • Use –restartFinder for immediate effect during managed sessions.
  • Combine with NinjaOne’s scheduling or remediation tools for persistent enforcement.
  • Log the output for auditing or troubleshooting.
  • Test on a subset of machines before full deployment to verify user behavior.

Final Thoughts

Shell scripting remains a powerful tool for macOS administration, especially when managing user preferences at scale. This script is a practical solution for IT professionals who need to enable or disable file extension visibility quickly and consistently across multiple users and devices.

With NinjaOne, this capability is elevated. Admins can deploy the script remotely, monitor execution success, and automate its use based on policy events. Whether you’re managing a school, a corporate fleet, or a mixed-user environment, this tool—alongside NinjaOne—empowers you to maintain a secure, predictable macOS experience.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service delivery 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).