How to Enable or Disable Hidden Files on macOS with Shell Script

Learning how to enable or disable hidden files on macOS with shell script is a common task for IT administrators. While macOS includes native GUI toggles and terminal commands for this purpose, these methods often fall short in enterprise environments where automation, consistency, and cross-user implementation are paramount. For Managed Service Providers (MSPs) and IT professionals managing fleets of Apple devices, scripting this behavior is a time-saving solution that enforces policy and simplifies onboarding workflows.

Background

Hidden files and folders on macOS typically include system configuration files, user preferences, and metadata that Apple has deemed unnecessary for average users. These files are usually prefixed with a dot (.) and play a critical role in system operations. For most users, hiding these elements reduces clutter and minimizes the risk of accidental modifications. However, developers, system admins, and power users often need to see these files for diagnostics, configuration changes, or auditing purposes.

Traditionally, visibility settings can be changed manually via terminal commands like defaults write com.apple.finder AppleShowAllFiles -bool true followed by restarting Finder. However, these methods are limited to individual user sessions and require manual intervention. The provided shell script elevates this capability by enabling or disabling hidden file visibility globally across all users using macOS system preferences.

The Script

#!/usr/bin/env bash
#
# Description: Enable or disable the viewing of hidden files and folders for all users.
# 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).
#
# Preset Parameter: --action "ReplaceMeWithYourDesiredAction"
#		Specify whether you would like to disable or enable the viewing of hidden files or folders.
#
# Preset Parameter: --restartFinder
#		You may need to restart Finder for this script to take effect immediately.
#
# Preset Parameter: --help
#		Displays some help text.
#
# Release Notes: Initial Release

# Initialize the variables used to store the action and the Finder restart flag
_arg_action=
_arg_restartFinder="off"

# This function prints the help menu with usage information and descriptions of the parameters
print_help() {
  printf '\n\n%s\n\n' 'Usage: [--action|-a <arg>] [--restartFinder|-r] [--help|-h]'
  printf '%s\n' 'Preset Parameter: --action "ReplaceMeWithYourDesiredAction"'
  printf '\t%s\n' "Specify whether you would like to disable or enable the viewing of hidden files or folders."
  printf '%s\n' 'Preset Parameter: --restartFinder'
  printf '\t%s\n' "You may need to restart Finder for this script to take effect immediately. Check this box to do so upon completion."
  printf '%s\n' 'Preset Parameter: --help'
  printf '\t%s\n' "Displays this help menu."
}

# This function is used to handle errors and terminate the script. 
die() {
  local _ret="${2:-1}"
  echo "$1" >&2
  test "${_PRINT_HELP:-no}" = yes && print_help >&2
  exit "${_ret}"
}

# This function processes the command-line arguments passed to the script.
parse_commandline() {
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --Action | --action | -a)
      test $# -lt 2 && die "[Error] Missing value for the required argument '$_key'." 1
      _arg_action=$2
      shift
      ;;
    --action=*)
      _arg_action="${_key##--action=}"
      ;;
    --restartFinder | --RestartFinder | --restartfinder | -r)
      _arg_restartFinder="on"
      ;;
    --help | -h)
      _PRINT_HELP=yes die "" 0
      ;;
    *)
      _PRINT_HELP=yes die "[Error] Got an unexpected argument '$1'" 1
      ;;
    esac
    shift
  done
}

# Parse the command-line arguments
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 _arg_action is not empty, trim any whitespace and convert it to lowercase
if [[ -n $_arg_action ]]; then
  _arg_action=$(echo "$_arg_action" | xargs | tr '[:upper:]' '[:lower:]')
fi

# If no valid action was provided, print an error message and exit the script
if [[ -z $_arg_action ]]; then
  _PRINT_HELP=yes die "[Error] No valid action was provided. Please specify either 'Enable' or 'Disable'." 1
fi

# Validate the action. If it is not "enable" or "disable", print an error and exit
if [[ $_arg_action != "enable" && $_arg_action != "disable" ]]; then
  _PRINT_HELP=yes die "[Error] The action '$_arg_action' is invalid. Please specify either 'Enable' or 'Disable'." 1
fi

# Based on the action, set the value for showing hidden files and folders
case "$_arg_action" in
enable)
  echo "Enabling 'Show hidden files and folders' for all users."
  _arg_showHiddenFilesValue="TRUE"
  ;;
disable)
  echo "Disabling 'Show hidden files and folders' for all users."
  _arg_showHiddenFilesValue="FALSE"
  ;;
esac

# Read the current value of the hidden file setting from the global preferences
currentHiddenFileValue=$(defaults read /Library/Preferences/.GlobalPreferences AppleShowAllFiles 2>&1)

# If the current setting matches the requested value, print a message indicating that no change is needed
if [[ "$currentHiddenFileValue" == "$_arg_showHiddenFilesValue" ]]; then
  case "$_arg_action" in
  enable)
    echo "'Show hidden files and folders' has already been enabled for all users."
    ;;
  disable)
    echo "'Show hidden files and folders' has already been disabled for all users."
    ;;
  esac
fi

# If the current setting is different from the requested value, attempt to update it
if [[ "$currentHiddenFileValue" != "$_arg_showHiddenFilesValue" ]]; then
  if ! setHiddenFileValueOutput=$(defaults write /Library/Preferences/.GlobalPreferences AppleShowAllFiles "$_arg_showHiddenFilesValue" 2>&1); then
    echo "[Error] Failed to update the hidden files or folders setting." >&2
    _PRINT_HELP=no die "[Error] $setHiddenFileValueOutput" 1
  else
    case "$_arg_action" in
    enable)
      echo "'Show hidden files and folders' has been successfully enabled for all users."
      ;;
    disable)
      echo "'Show hidden files and folders' has been successfully disabled for all users."
      ;;
    esac
  fi
fi

# If the restartFinder flag is "on", restart Finder as requested and handle any errors
if [[ $_arg_restartFinder == "on" ]]; then
  echo "Restarting Finder as requested."

  if ! restartFinderOutput=$(killall Finder 2>&1); then
    echo "[Error] Failed to restart Finder." >&2
    _PRINT_HELP=no die "[Error] $restartFinderOutput" 1
  else
    echo "Successfully restarted Finder."
  fi
fi

 

Detailed Breakdown

This Enable or Disable Show Hidden Files or Folders macOS shell script is designed with clarity, robustness, and automation in mind. Here’s a breakdown of its operations:

  1. Argument Parsing
    • The script expects an –action parameter, which can be set to either Enable or Disable, and optionally a –restartFinder flag to immediately apply changes.
    • It normalizes and validates inputs, converting values to lowercase for consistency and ensuring required arguments are provided.
  2. Action Validation
    • Invalid or missing actions are caught early, with helpful error messages and a printed help guide for users unfamiliar with the syntax.
  3. Read Current Setting
    • The script checks the current value of the AppleShowAllFiles preference stored under /Library/Preferences/.GlobalPreferences, ensuring it only makes changes if necessary.
  4. Modify System Preferences
    • If the value differs from the desired state, the script writes the new setting using defaults write.
  5. Restart Finder (Optional)
    • If the user specifies –restartFinder, the script will kill and restart the Finder process to apply the change immediately.

This modular structure ensures the script is not only functional but also safe and informative in its execution.

Potential Use Cases

Consider a managed IT environment at a software development firm where several teams work with dotfiles (e.g., .env, .gitignore, .bash_profile). An MSP managing these devices might use this script to enable the viewing of hidden files during onboarding to streamline access to configuration files. Conversely, when decommissioning or handing over machines to non-technical roles, the same script could be used to disable visibility for security and cleanliness.

Through an RMM platform like NinjaOne, this script can be deployed fleet-wide with consistent parameters, ensuring devices conform to organizational standards without manual oversight.

Comparisons

Manual Method:

  • defaults write com.apple.finder AppleShowAllFiles TRUE; killall Finder
    • Only affects the current user.
    • Must be run manually on each machine.

Profile Configuration via MDM:

  • More robust but significantly more complex to configure.
  • Requires Apple Push Certificate and management server integration.

This Script:

  • Simple, portable, and easily automated.
  • Suitable for all users on a system.
  • Can be conditionally executed with restarts built-in.

Compared to GUI toggles or user-local terminal commands, this shell script provides an efficient, repeatable, and auditable solution.

FAQs

Q: Will this script change the setting for all users or just the current user?

A: This script modifies the global system preference, affecting all users on the machine.

Q: Do I need administrative privileges to run this script?

A: Yes, modifying /Library/Preferences/.GlobalPreferences requires elevated permissions.

Q: What happens if Finder isn’t restarted?

A: Changes won’t take effect immediately. Users must restart Finder manually or with the script’s –restartFinderoption.

Q: Is this script compatible with all macOS versions?

A: It is compatible with all modern versions that still use .GlobalPreferences and Finder. However, always test on a sample device before large-scale deployment.

Implications

Changing hidden file visibility has subtle but significant implications in an enterprise. Enabling visibility increases transparency and aids in troubleshooting but also introduces risk if end-users mistakenly alter critical hidden files. Conversely, disabling visibility enhances security and UI simplicity but can hinder developer productivity. Understanding these trade-offs is crucial when integrating this script into organizational policy.

Recommendations

  • Audit Before Rollout: Always check the current configuration state and ensure this change aligns with organizational policy.
  • Pair with RMM Policies: Deploy via NinjaOne to apply this setting across device groups or organizational units.
  • Use with Logging: Integrate with logging tools to capture script execution results for compliance auditing.
  • Provide Documentation: If enabling hidden files, provide end-users with training or documentation to prevent misuse.

Final Thoughts

This Show or Hide Hidden Files or Folders macOS shell script offers IT professionals and MSPs a practical, scalable method for controlling Finder visibility settings. When used in conjunction with NinjaOne, the script becomes a powerful automation asset—capable of being deployed on demand, audited centrally, and integrated into broader device configuration workflows.

Whether you’re standardizing developer environments or securing endpoints for general users, this script simplifies a once-manual task with professionalism and precision.

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