dscl - macOS


Overview

dscl (Directory Service command line utility) is a command-line tool used on macOS for managing and querying Directory Services. It allows you to interact with the directory services data store, which includes user accounts, groups, and other directory-based data. It is primarily used by system administrators for scripting and automation of account management tasks, making it highly effective for large-scale deployments and local machine configuration.

Syntax

The basic syntax of the dscl command is as follows:

dscl [options] <datasource> <verb> [options and arguments for verb]

Where:

  • <datasource> can be a domain name or a node name (/Local/Default, /LDAPv3/127.0.0.1, etc.).
  • <verb> can be actions like read, create, delete, edit, etc.

Options/Flags

  • -u : Use this flag to specify the admin user for operations that require elevated privileges.
  • -p: Read password from standard input, used together with -u.
  • -f : Execute commands from a specified file.
  • -raw: Display unformatted record and attribute values.
  • -plist: Output results in XML plist format.

Commonly Used Verbs

  • read: Reads the values of a record or property.
  • create: Creates a new record or adds a new value.
  • delete: Deletes a record or removes a value.
  • list: Lists records within a specified category.
  • search: Search for records matching the criteria.

Examples

  1. List all users on the system:

    dscl . -list /Users
    
  2. Create a new user:

    sudo dscl . -create /Users/newuser
    sudo dscl . -create /Users/newuser UserShell /bin/bash
    sudo dscl . -create /Users/newuser RealName "New User"
    sudo dscl . -create /Users/newuser UniqueID 1001
    sudo dscl . -create /Users/newuser PrimaryGroupID 100
    sudo dscl . -passwd /Users/newuser password
    
  3. Delete a user:

    sudo dscl . -delete /Users/olduser
    

Common Issues

  • Permissions: Failure to include sudo when needed results in permission errors.
  • Unique ID conflicts: Ensure that the UniqueID assigned to new users does not conflict with existing users.

Integration

dscl can be combined with other commands for more complex tasks. For instance, we can pipe the output of dscl to grep or awk for filtering or formatting:

dscl . -list /Users | grep "admin"

For scripting automation, integrating with bash scripts can enhance user management systems, automate backups, or sync local user data with remote systems.

  • dscacheutil: For flushing the directory service cache.
  • id: Query user identity information.

For more detailed documentation on dscl, you can refer to the man page by typing man dscl in the terminal or visiting the official macOS command line documentation.