readonly - macOS


Overview

readonly is a macOS command that allows you to make a file or directory read-only, preventing any modifications or deletions. It is commonly used to protect critical system files, configuration settings, or sensitive data from accidental or malicious changes.

Syntax

readonly [-R] [-v] [-P] path...

Options/Flags

  • -R: Recursively apply read-only permissions to all files and directories within the specified path.
  • -v: Print verbose output showing the status of each file or directory.
  • -P: By default, readonly follows symbolic links. This flag prevents following symbolic links.

Examples

  • Make a single file read-only:
readonly /path/to/file.txt
  • Make a directory and its contents read-only recursively:
readonly -R /path/to/directory
  • Print verbose output while making a file read-only:
readonly -v /path/to/file.txt

Common Issues

  • Permission denied error: Ensure you have sufficient permissions to modify the file or directory. Try using sudo if necessary.
  • File or directory is already read-only: The file or directory may already have read-only permissions set. Use the ls -l command to check the file permissions.

Integration

readonly can be integrated with other commands for advanced tasks, such as:

  • find: Find and make all files with a specific pattern read-only:
find /path/to/directory -name '*.txt' -exec readonly {} +
  • chmod: Change file permissions to read-only using readonly and chmod:
readonly /path/to/file.txt && chmod a-w /path/to/file.txt
  • chflags: Set file flags, including read-only and immutable flags.
  • chmod: Change file permissions.
  • ls -l: Display file permissions and attributes.