magnusviri

CLI

Decades ago I wrote the OS X Terminal page.

Now I need a page to discuss certain CLI stuff that I always forget (mostly macOS, but others as well).

Quicknotes

View mounts: mount, mount on boot edit /etc/fstab

ps aux

Similar to telnet: nc -z 10.0.0.1 22

See memory usage: free -m, free -g, vmstat -a

Find open ports: sudo lsof -i, netstat -avn or on Linux: sudo netstat -tulpn, systemctl status <name> or service <name> status

Find free space: df -ah

Find folder usage du -sh /path

log stream --predicate subsystem == "*"

Built-in macOS CLI tools

Here is a full list of macOS cli tools. Here are a few that I want to highlight.

afplay

    Audio File Play
    Version: 2.0
    Copyright 2003-2013, Apple Inc. All Rights Reserved.
    Specify -h (-help) for command options

Usage:
afplay [option...] audio_file

Options: (may appear before or after arguments)
  {-v | --volume} VOLUME
    set the volume for playback of the file
  {-h | --help}
    print help
  { --leaks}
    run leaks analysis
  {-t | --time} TIME
    play for TIME seconds
  {-r | --rate} RATE
    play at playback rate
  {-q | --rQuality} QUALITY
    set the quality used for rate-scaled playback (default is 0 - low quality, 1 - high quality)
  {-d | --debug}
    debug print output

caffeinate

usage: caffeinate [-disu] [-t timeout] [-w Process ID] [command arguments...]

csrutil

usage: csrutil <command>
Modify the System Integrity Protection configuration.
Available commands:

    clear
        Clear the existing configuration.
    disable
        Disable the protection of the OS installation. Only available in Recovery OS.
    enable
        Enable the protection of the OS installation. Only available in Recovery OS.
    status
        In Recovery OS, displays the configuration for each OS installation.
        In macOS, displays the configuration of the running OS.

    allow-research-guests
        status
            Show the current allow research guests setting.
        disable
            Disallow research guests. Only available in Recovery OS.
        enable
            Allow research guests. Only available in Recovery OS.

    authenticated-root
        status
            Show the current authenticated root setting.
        disable
            Allow booting from non-sealed system snapshots. Only available in Recovery OS.
        enable
            Only allow booting from sealed system snapshots. Only available in Recovery OS.

dscacheutil

Usage: dscacheutil -h
       dscacheutil -q category [-a key value]
       dscacheutil -cachedump [-buckets] [-entries [category]]
       dscacheutil -configuration
       dscacheutil -flushcache
       dscacheutil -statistics

diskutil

Disk Utility Tool
Utility to manage local disks and volumes
Most commands require an administrator or root user

WARNING: Most destructive operations are not prompted

Usage:  diskutil [quiet] <verb> <options>, where <verb> is as follows:

     list                 (List the partitions of a disk)
     info[rmation]        (Get information on a specific disk or partition)
     listFilesystems      (List file systems available for formatting)
     listClients          (List all current disk management clients)
     activity             (Continuous log of system-wide disk arbitration)

     u[n]mount            (Unmount a single volume)
     unmountDisk          (Unmount an entire disk (all volumes))
     eject                (Eject a disk)
     mount                (Mount a single volume)
     mountDisk            (Mount an entire disk (all mountable volumes))

     enableJournal        (Enable HFS+ journaling on a mounted HFS+ volume)
     disableJournal       (Disable HFS+ journaling on a mounted HFS+ volume)
     moveJournal          (Move the HFS+ journal onto another volume)
     enableOwnership      (Exact on-disk User/Group IDs on a mounted volume)
     disableOwnership     (Ignore on-disk User/Group IDs on a mounted volume)

     rename[Volume]       (Rename a volume)

     verifyVolume         (Verify the file system data structures of a volume)
     repairVolume         (Repair the file system data structures of a volume)
     verifyDisk           (Verify the components of a partition map of a disk)
     repairDisk           (Repair the components of a partition map of a disk)
     resetFusion          (Reset the components of a machine's Fusion Drive)

     eraseDisk            (Erase an existing disk, removing all volumes)
     eraseVolume          (Erase an existing volume)
     reformat             (Erase an existing volume with same name and type)
     eraseOptical         (Erase optical media (CD/RW, DVD/RW, etc.))
     zeroDisk             (Erase a disk, writing zeros to the media)
     randomDisk           (Erase a disk, writing random data to the media)
     secureErase          (Securely erase a disk or freespace on a volume)

     partitionDisk        ((re)Partition a disk, removing all volumes)
     addPartition         (Create a new partition to occupy free space)
     splitPartition       (Split an existing partition into two or more)
     mergePartitions      (Combine two or more existing partitions into one)
     resizeVolume         (Resize a volume, increasing or decreasing its size)

     appleRAID <verb>     (Perform additional verbs related to AppleRAID)
     coreStorage <verb>   (Perform additional verbs related to CoreStorage)
     apfs <verb>          (Perform additional verbs related to APFS)
     image <verb>         (Perform additional verbs related to DiskImage)

diskutil <verb> with no options will provide help on that verb

hdiutil

Usage: hdiutil <verb> <options>
<verb> is one of the following:
help            	imageinfo
attach          	isencrypted
detach          	makehybrid
eject           	mount
verify          	mountvol
create          	unmount
compact         	plugins
convert         	resize
burn            	segment
info            	pmap
checksum        	udifderez
chpass          	udifrez
erasekeys

hidutil

Usage:

  hidutil [command]

Available commands:
  help       - print this help message
  dump       - dump HID Event System state
  property   - read/write HID Event System property
  list       - list HID Event System services and devices

Use "hidutil [command] --help" for more information about a command.

iconutil

Usage: iconutil --convert ( icns | iconset) [--output file] file [icon-name]

mdutil

Usage: mdutil -pEsa -i (on|off) -d volume ...
       mdutil -t {volume-path | deviceid} fileid
	Utility to manage Spotlight indexes.
	-i (on|off)    Turn indexing on or off.
	-d             Disable Spotlight activity for volume (re-enable using -i on).
	-E             Erase and rebuild index.
	-s             Print indexing status.
	-a             Apply command to all stores on all volumes.
	-t             Resolve files from file id with an optional volume path or device id.
	-p             Publish metadata.
	-V vol         Apply command to all stores on the specified volume.
	-v             Display verbose information.
	-r plugins     Ask the server to reimport files for UTIs claimed by the listed plugin.
	-L volume-path List the directory contents of the Spotlight index on the specified volume.
	-P volume-path Dump the VolumeConfig.plist for the specified volume.
	-X volume-path Remove the Spotlight index directory on the specified volume.  Does not disable indexing.
	               Spotlight will reevaluate volume when it is unmounted and remounted, the
	               machine is rebooted, or an explicit index command such as 'mdutil -i' or 'mdutil -E' is
	               run for the volume.
NOTE: Run as owner for network homes, otherwise run as root.

notifyutil

notification command line utility

usage: notifyutil [-q] [-v] [-z msec] [-M] [-R] [command ...]
    -q             quiet mode
    -v             verbose - prints time, key, state value, and type
    -z msec        pause msec milliseconds after posting [default 100]
    -M             multiplex notifications from notifyd over a single mach port
    -R             regenerate registrations if notifyd restarts
commands:
    -port          switch to mach port for subsequent registrations [default]
    -file          switch to file descriptor for subsequent registrations
    -check         switch to shared memory for subsequent registrations
    -signal [#]    switch to signal [#] for subsequent registrations
                   initial default for signal is 1 (SIGHUP)
    -dispatch      switch to dispatch for subsequent registrations
    -p key         post a notification for key
    -w key         register for key and report notifications
    -# key         (# is an integer value, eg "-1") register for key and report # notifications
    -g key         get state value for key
    -s key val     set state value for key

odutil

allows caller to examine or change state of opendirectoryd(8)

Usage: odutil show [cache | nodes | requests | connections | sessions | nodenames | users | statistics | all]
Usage: odutil show configuration <nodename> [module <modulename>] [option <option>]
Usage: odutil set log [default | alert | critical | error | warning | notice | info | debug]
Usage: odutil set statistics [off | on]
Usage: odutil set configuration <nodename> [module <modulename>] option <option> <value>
Usage: odutil reset [cache | statistics]

pkgutil

Usage: pkgutil [OPTIONS] [COMMANDS] ...

Options:
  --help                 Show this usage guide
  --verbose, -v          Show contextual information and format for easy reading
  --force, -f            Perform all operations without asking for confirmation
  --volume PATH          Perform all operations on the specified volume
  --edit-pkg PKGID       Adjust properties of package PKGID using --learn PATH
  --only-files           List only files (not directories) in --files listing
  --only-dirs            List only directories (not files) in --files listing
  --regexp               Try all PKGID arguments as regular expressions

Receipt Database Commands:
  --pkgs, --packages     List all currently installed package IDs on --volume
  --pkgs-plist           List all package IDs on --volume in plist format
  --pkgs=REGEXP          List package IDs on --volume that match REGEXP
  --groups               List all GROUPIDs on --volume
  --groups-plist         List all GROUPIDs on --volume in plist format
  --group-pkgs GROUPID   List all PKGIDs in GROUPID
  --files PKGID          List files installed by the specified package
  --lsbom PKGID          List files in the same format as 'lsbom -s'
  --pkg-groups PKGID     List all GROUPIDs that PKGID is a member of
  --export-plist PKGID   Print all info about PKGID in plist format
  --pkg-info PKGID       Show metadata about PKGID
  --pkg-info-plist PKGID Show metadata about PKGID in plist format
  --file-info PATH       Show metadata known about PATH
  --file-info-plist PATH Show metadata known about PATH in plist format
  --forget PKGID         Discard receipt data for the specified package
  --learn PATH           Update --edit-pkg PKGID with actual metadata from PATH

File Commands:
  --expand PKG DIR       Expand the flat package PKG to DIR
  --flatten DIR PKG      Flatten the files at DIR as PKG
  --bom PATH             Extract any Bom files from the pkg at PATH into /tmp
  --payload-files PATH   List the paths archived within the (m)pkg at PATH
  --check-signature PATH Validate the signature of the pkg at PATH and print certificate information

plutil

plutil -lint
plutil -convert xml1
plutil -convert binary1
plutil -convert json

/usr/libexec/PlistBuddy

My plcat script:

#!/bin/sh

for ii in "$@"; do
	if [ -f "$ii" ]; then
		/usr/libexec/PlistBuddy -c Print -x "$ii"
		# cat "$ii" | plutil -convert xml1 - -o -
	else
		echo File not found: $ii
	fi
done

scutil

usage: scutil
	interactive access to the dynamic store.

   or: scutil --prefs [preference-file]
	interactive access to the [raw] stored preferences.

   or: scutil [-W] -r nodename
   or: scutil [-W] -r address
   or: scutil [-W] -r local-address remote-address
	check reachability of node, address, or address pair (-W to "watch").

   or: scutil -w dynamic-store-key [ -t timeout ]
	-w	wait for presense of dynamic store key
	-t	time to wait for key

   or: scutil --get pref
   or: scutil --set pref [newval]
   or: scutil --get filename path key
	pref	display (or set) the specified preference.  Valid preferences
		include:
			ComputerName, LocalHostName, HostName
	newval	New preference value to be set.  If not specified,
		the new value will be read from standard input.

   or: scutil --dns
	show DNS configuration.

   or: scutil --proxy
	show "proxy" configuration.

   or: scutil --nwi
	show network information

   or: scutil --nc
	show VPN network configuration information. Use --nc help for full command list

   or: scutil --renew [interface-name]
	re-evaluate network configuration on the interface.

   or: scutil --allow-new-interfaces [off|on]
	manage new interface creation with screen locked.

   or: scutil --error err#
	display a descriptive message for the given error code

smbutil

usage: smbutil [-hv] subcommand [args]
where subcommands are:
 help          display help on specified subcommand
 lookup        resolve NetBIOS name to IP address
 status        resolve IP address or DNS name to NetBIOS names
 view          list resources on specified host
 dfs           list DFS referrals
 identity      identity of the user as known by the specified host
 statshares    list the attributes of mounted share(s)
 multichannel  list the attributes of the channels of mounted share(s)
 snapshot      list snapshots for the mount path
 smbstat       list info about item at path

sysadminctl

sysadminctl
Usage: sysadminctl
	-deleteUser <user name> [-secure || -keepHome] (interactive || -adminUser <administrator user name> -adminPassword <administrator password>)
	-newPassword <new password> -oldPassword <old password> [-passwordHint <password hint>]
	-resetPasswordFor <local user name> -newPassword <new password> [-passwordHint <password hint>] (interactive] || -adminUser <administrator user name> -adminPassword <administrator password>)
	-addUser <user name> [-fullName <full name>] [-UID <user ID>] [-GID <group ID>] [-shell <path to shell>] [-password <user password>] [-hint <user hint>] [-home <full path to home>] [-admin] [-roleAccount] [-picture <full path to user image>] (interactive] || -adminUser <administrator user name> -adminPassword <administrator password>)
	-secureTokenStatus <user name>
	-secureTokenOn <user name> -password <password> (interactive || -adminUser <administrator user name> -adminPassword <administrator password>)
	-secureTokenOff <user name> -password <password> (interactive || -adminUser <administrator user name> -adminPassword <administrator password>)
	-autologin set -userName <user name> [-password <user password>] || off || status (interactive || -adminUser <administrator user name> -adminPassword <administrator password>)
	-guestAccount <on || off || status>
	-afpGuestAccess <on || off || status>
	-smbGuestAccess <on || off || status>
	-automaticTime <on || off || status>
	-use12HourClockForLoginWindow <on || off || status>
	-filesystem status
	-screenLock <status || immediate || off || seconds> -password <password>

Pass '-' instead of password in commands above to request prompt.
'-adminPassword' used mostly for scripted operation. Use '-' or 'interactive' to get the authentication string interactively. This preferred for security reasons

	*Role accounts require name starting with _ and UID in 450-499 range.

tccutil

tccutil: Usage: tccutil reset SERVICE [BUNDLE_ID]

textutil

textutil: [command_option] [other_options] file...
Command options are (-help is the default):
 -help          show this message and exit
 -info          display information about each file
 -convert fmt   convert each input file to format (txt, rtf, rtfd,
                html, doc, docx, odt, wordml, or webarchive)
 -cat fmt       concatenate input files into one output file
...

txt, rtf, rtfd, html, doc, docx, odt, wordml, or webarchive

It's 2025 and Apple still continues to ignore Markdown, which has taken over the tech world and was created by Apple blogger John Gruber who has interviewed top Apple execs.

tmutil

Usage: tmutil addexclusion [-p|-v] item ...
Usage: tmutil associatedisk [-a] mount_point volume_backup_directory
Usage: tmutil calculatedrift machine_directory
Usage: tmutil compare [-@acdefghlmnstuEX] [-D depth] [-I name]
       tmutil compare [-@acdefghlmnstuEX] [-D depth] [-I name] snapshot_path
       tmutil compare [-@acdefghlmnstuEUX] [-D depth] [-I name] path1 path2
Usage: tmutil delete [-d backup_mount_point -t timestamp] [-p path]
Usage: tmutil deleteinprogress machine_directory
Usage: tmutil deletelocalsnapshots [<mount_point> | <snapshot_date>]
Usage: tmutil destinationinfo [-X]
Usage: tmutil disable
Usage: tmutil enable
Usage: tmutil help verb
Usage: tmutil inheritbackup machine_directory
       tmutil inheritbackup sparse_bundle
Usage: tmutil isexcluded item ...
Usage: tmutil latestbackup [-m] [-t] [-d mount_point]
Usage: tmutil listbackups [-m] [-t] [-d mount_point]
Usage: tmutil listlocalsnapshotdates [<mount_point>]
Usage: tmutil listlocalsnapshots <mount_point>
Usage: tmutil localsnapshot
Usage: tmutil machinedirectory
Usage: tmutil removedestination destination_id
Usage: tmutil removeexclusion [-p|-v] item ...
Usage: tmutil restore [-v] src ... dst
Usage: tmutil setdestination [-a]  mount_point
       tmutil setdestination [-ap] afp://user[:pass]@host/share
Usage: tmutil setquota destination_id quota_in_gigabytes
Usage: tmutil startbackup [-a | --auto] [-b | --block] [-r | --rotation] [-d | --destination dest_id]
Usage: tmutil stopbackup
Usage: tmutil thinlocalsnapshots <mount_point> [purgeamount] [urgency]
Usage: tmutil uniquesize path ...
Usage: tmutil verifychecksums path ...
Usage: tmutil version

wdutil

usage: sudo wdutil diagnose [-q] [-f outputDirectoryPath]
            -q may be specified to suppress legal prompt and Finder window
       sudo wdutil info
       sudo wdutil log [{+|-} {system|wifi}]+
       sudo wdutil dump
       sudo wdutil clean
       sudo wdutil privateMAC={0/1}

Installable tools

Not all of these are macOS only.

ansible
asciinema
bash
black
duti
huggingface-cli
jq
lolcat
luarocks
mactop
micro
mist
ncat
nmap
ollama
pipenv
prettier
prettyping
pstops
pstree
rename
s3cmd
tart
uv
webpinfo
wumpus
zsh

Jamf bash script

Probably one of the most useful things I did with Jamf was create a script that just runs the args as bash commands. Here's the script.

#!/usr/bin/perl -w

use strict;

# %MOUNT %COMP %USER are replaced with $ARGV[0], $ARGV[1], $ARGV[2] respectively.

$ENV{HOME} = '/var/root';

my ( $mount_point, $computer_name, $username ) = splice(@ARGV,0,3);
my $exit = 0;

for my $arg ( @ARGV ) {
	if ( $arg ne '' and $arg !~ /^#/ ) {
		$arg =~ s/%MOUNT/$mount_point/;
		$arg =~ s/%COMP/$computer_name/;
		$arg =~ s/%USER/$username/;
		#print "$arg\n";
		$exit += 1 if system $arg;
	}
}
exit $exit;

Here's some examples of how I use it.

Script that sets computer name (we clear out HostName because I find it problematic in our environment).

Enrollment complete policy

Published: 2025-07-10, last edited: 2025-07-10, Copyright © 2025 James Reynolds