Secret Mac Terminal Commands: Unlock Advanced Features for Power Users

47次阅读
没有评论

The graphical user interface (GUI) of macOS is renowned for its elegance, intuitiveness, and user-friendliness. For the vast majority of users, the Finder, System Settings, and various applications provide all the functionality they could ever need. But beneath this polished veneer lies a powerful beast, an intricate system accessible through the Terminal. For the power user, the Terminal isn’t just a relic of computing’s past; it’s a direct gateway to deeper system controls, hidden settings, and efficiencies that the GUI simply doesn’t offer.

This article delves into a collection of “secret” or lesser-known Terminal commands designed to empower macOS power users. These commands allow you to manipulate your system, customize your environment, troubleshoot issues, and gain insights far beyond what standard graphical tools provide. While some may seem intimidating at first, understanding and utilizing them can transform your macOS experience, boosting productivity and granting you an unparalleled level of control.

A Crucial Disclaimer: The Terminal is incredibly powerful. With great power comes great responsibility. Many commands, especially those prefixed with sudo (superuser do), can make fundamental changes to your system. Always understand what a command does before executing it. Incorrect commands can lead to data loss, system instability, or even render your Mac unbootable. When in doubt, search for more information or refrain from execution. Proceed with caution and curiosity!

Master Your Mac’s Core System

Gaining a deeper understanding and control over your Mac’s fundamental operations is the first step towards becoming a true power user. These commands offer insights and manipulation capabilities for your hardware and basic system behaviors.

1. Get Detailed CPU Information

You might know your Mac has an M-series chip or an Intel Core i7, but what about the specifics? The sysctl command can reveal intricate hardware details.

sysctl -n machdep.cpu.brand_string

This command will output the exact model string of your CPU, for example: “Apple M2 Pro” or “Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz”. It’s a quick way to verify hardware or satisfy your inner tech enthusiast.

2. Diagnose Power & Sleep Issues

Is your Mac waking up unexpectedly? Or perhaps not sleeping when it should? The pmset command is your go-to for power management diagnostics and configuration.

pmset -g log | grep "Wake from"

This command filters your power management logs to show only instances where your Mac woke up, helping you identify patterns or specific events causing unwanted wake-ups.

To schedule specific wake-up or sleep times:

sudo pmset schedule wake "MM/DD/YY HH:MM:SS"
sudo pmset schedule sleep "MM/DD/YY HH:MM:SS"

Replace the date and time with your desired schedule. Remember to use sudo for scheduling changes.

3. Prevent Your Mac From Sleeping (Caffeinate It!)

Sometimes you need your Mac to stay awake for an extended period, perhaps during a long download, a large file transfer, or a lengthy compilation. While there are GUI apps for this, the Terminal offers a built-in solution.

caffeinate -i

This command will prevent your Mac from going to sleep due to inactivity for as long as the Terminal window is open and the command is running. The -i flag ensures it prevents idle sleep, while other flags can prevent display sleep (-d), disk sleep (-m), or even system sleep (-s). Press Control+C to stop the command.

4. Purge Inactive RAM

While macOS is generally excellent at managing RAM, sometimes you might want to force a clear of inactive memory pages, especially after closing a memory-intensive application.

sudo purge

This command attempts to free up inactive memory. It doesn’t necessarily make your system faster, as macOS will aggressively cache data it thinks you might need again. However, in specific scenarios, like after closing a virtual machine or a video editor, it can be useful to quickly reclaim a large chunk of RAM. Use sparingly, as macOS generally knows best how to manage its memory.

5. Check System Integrity Protection (SIP) Status

System Integrity Protection (SIP), introduced in El Capitan, is a vital security feature that prevents even root users from modifying certain system files and processes. For power users who might dabble in deeper system customizations, knowing its status is crucial.

csrutil status

This command will report whether SIP is enabled or disabled. While disabling SIP is generally not recommended for security reasons, it’s sometimes necessary for certain development tasks or very deep system customizations. Enabling/disabling SIP requires booting into Recovery Mode.

Deep Dive into File & Folder Management

The Finder is great, but the Terminal offers unparalleled precision and power when dealing with files and folders, especially when you need to handle hidden items, metadata, or batch operations.

6. Show Hidden Files in Finder

One of the most frequently sought-after power user tricks is showing hidden files (those starting with a .) in Finder. While there’s a keyboard shortcut (Cmd+Shift+.), the Terminal command offers a more “permanent” toggle until you revert it.

defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder

To hide them again, simply change true to false:

defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder

The killall Finder command is essential to apply the changes immediately, as it restarts the Finder process.

7. Hide/Unhide Specific Files or Folders

Beyond showing all hidden files, you might want to specifically hide or unhide a particular file or folder, without renaming it to start with a dot.

chflags hidden /path/to/file_or_folder
chflags nohidden /path/to/file_or_folder

This command modifies the file’s flags at the Unix level. Hidden items will still be visible if “Show Hidden Files” is enabled in Finder, but otherwise, they’ll disappear from view.

8. Remove Extended Attributes (e.g., Quarantine)

When you download files from the internet, macOS often applies a “quarantine” attribute, warning you before opening them. While a security feature, it can be annoying for trusted files or when dealing with large batches of downloaded items.

xattr -cr /path/to/folder

This command recursively (-r) clears (-c) all extended attributes (xattr) from files within the specified folder. This is particularly useful for dealing with downloaded development tools or large archives where you trust the source and don’t want to click through multiple warnings. Use with caution!

9. Spotlight Search from the Terminal

Spotlight is powerful, but sometimes you want its indexing capabilities within your command-line workflow. The mdfind command allows you to search your Mac’s Spotlight index directly.

mdfind "kind:folder kMDItemDisplayName =='*backup*'"

This example searches for folders (kind:folder) whose display name (kMDItemDisplayName) contains “backup”. You can use various Spotlight metadata attributes (e.g., kMDItemKind, kMDItemCreator, kMDItemFSName, etc.) for highly specific searches.

10. Advanced Archiving with Metadata

The zip command is common, but ditto offers more powerful options, especially for preserving macOS-specific metadata, resource forks, and permissions when archiving.

ditto -c -k --sequesterRsrc --keepParent src_directory archive.zip
  • -c: Create archive
  • -k: Compress using PKZip format
  • --sequesterRsrc: Preserve resource forks and other metadata
  • --keepParent: Include the parent directory in the archive structure

This is ideal for backing up entire application bundles or folders where preserving macOS-specific attributes is critical.

Network & Security Prowess

For network administrators, developers, or anyone keen on understanding their Mac’s network presence, the Terminal provides powerful tools for inspection and configuration.

11. Change Your Mac’s Hostname

Your Mac has several names: a Computer Name (displayed in Finder sidebar), a Local Hostname (used for network discovery, ending in .local), and a Hostname (the Unix name). While you can change the Computer Name in System Settings, the Local Hostname and Hostname can be managed via scutil.

sudo scutil --set LocalHostName "NewLocalHostName"
sudo scutil --set HostName "NewHostName"

Replace "NewLocalHostName" and "NewHostName" with your desired names. The LocalHostName is what other devices see on the local network (e.g., my-mac.local), while HostName is more for internal system use.

12. List Listening Network Ports

Curious which applications are listening for incoming network connections on your Mac? The lsof (list open files) command can reveal this, specifically for TCP ports.

sudo lsof -iTCP -sTCP:LISTEN

This command lists all processes that have TCP ports open and are in a LISTEN state, meaning they are waiting for incoming connections. This is invaluable for security audits or troubleshooting network-related application issues.

13. Flush DNS Cache

If you’re experiencing issues resolving domain names (e.g., a website isn’t loading correctly, even though it works on other devices), clearing your Mac’s DNS cache can often resolve the problem.

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

This two-part command first flushes the DNS resolver cache and then sends a HUP (hang up) signal to the mDNSResponder process, forcing it to reload its configuration and clear its internal cache.

14. View Routing Tables

Understanding how your Mac routes network traffic is essential for advanced networking and troubleshooting. The netstat command can display your Mac’s routing table.

netstat -rn

This command shows the network routing tables, detailing destination networks, gateway addresses, and network interfaces used for various routes. Useful for diagnosing complex network connectivity problems or verifying VPN configurations.

Customize Your macOS Experience

Many of the most popular “secret” Terminal commands are defaults write commands, which allow you to tweak hidden settings in various macOS applications and system behaviors that aren’t exposed in System Settings.

15. Speed Up Dock Auto-Hide Animation

If you use the Dock in auto-hide mode, you might find the slight delay before it hides or shows up to be a minor annoyance. You can eliminate this delay entirely.

defaults write com.apple.dock autohide-delay -float 0; killall Dock

This sets the delay to zero. To restore the default delay (which is around 0.5 seconds), you can use:

defaults delete com.apple.dock autohide-delay; killall Dock

16. Add Invisible Spacers to the Dock

For aesthetic purposes or to organize your Dock more effectively, you can add invisible spacers between app icons.

defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}'; killall Dock

Execute this command multiple times to add more spacers. To remove them, simply drag them off the Dock like any other icon, or reset the Dock:

defaults delete com.apple.dock persistent-apps; killall Dock

(Note: resetting persistent-apps will remove all user-added apps from the Dock, reverting to system defaults)

17. Hide Desktop Icons

For a minimalist desktop or when giving a presentation, you might want to hide all icons on your desktop without moving them.

defaults write com.apple.finder CreateDesktop false; killall Finder

Your desktop will instantly become blank. To bring them back:

defaults write com.apple.finder CreateDesktop true; killall Finder

18. Change Screenshot File Format

By default, macOS saves screenshots as PNG files. If you prefer JPG, TIFF, GIF, or PDF, you can easily change the default format.

defaults write com.apple.screencapture type JPG; killall SystemUIServer

Replace JPG with your desired format (e.g., PNG, TIFF, GIF, PDF). The killall SystemUIServer command restarts the menu bar process to apply the change.

19. Disable Mail App Animations

If you find the Mail app’s reply and compose animations slow or distracting, you can disable them for a snappier experience.

defaults write com.apple.mail DisableReplyAnimations -bool true
defaults write com.apple.mail DisableSendAnimations -bool true

You’ll need to quit and restart Mail for these changes to take effect. To re-enable them, change true to false.

Troubleshooting & Performance Tweaks

When things go wrong, or you need to squeeze out every bit of performance, the Terminal provides tools for deep diagnostics and system-level manipulation.

20. Stream Real-time System Logs

The Console app provides a GUI for viewing logs, but for real-time monitoring of system activity, nothing beats log stream in the Terminal.

log stream

This command displays a continuous stream of system logs, which can be invaluable for diagnosing application crashes, system errors, or tracking specific events as they happen. You can filter the output using various flags, e.g., log stream --predicate 'process =="Finder"' to only see Finder logs.

21. Inspect and Manage Background Processes (LaunchAgents/LaunchDaemons)

Many background processes on macOS are managed by launchd via LaunchAgents (per-user background tasks) and LaunchDaemons (system-wide background tasks). The launchctl command allows you to inspect and manage these.

launchctl list

This lists all currently loaded LaunchAgents and LaunchDaemons, showing their PID (process ID), status, and label. You can load, unload, or restart specific services:

launchctl unload ~/Library/LaunchAgents/com.example.agent.plist
launchctl load ~/Library/LaunchAgents/com.example.agent.plist

Be extremely cautious when unloading system-critical LaunchDaemons, as this can destabilize your system.

22. Advanced Disk Management

The Disk Utility app handles most common disk tasks, but for specific, scriptable, or more granular control, diskutil is the command-line equivalent.

diskutil list

This command lists all connected disks and their partitions, providing their identifiers (e.g., disk0, disk0s1). You can use these identifiers for operations like unmounting, erasing, or partitioning.

WARNING: These commands are highly destructive if used incorrectly. Always double-check the disk identifier.

To unmount a volume (e.g., a USB drive):

diskutil unmount /dev/diskXsY

To erase an entire disk (e.g., a USB drive, replacing diskX with the correct identifier):

sudo diskutil eraseDisk JHFS+ MyVolume /dev/diskX

This command erases diskX and formats it as Journaled HFS+ (macOS Extended), naming it “MyVolume”.

23. Image Conversion and Manipulation

The sips (scriptable image processing system) command is a powerful tool for batch processing and manipulating images directly from the Terminal.

sips -s format jpeg image.png --out image.jpeg

This example converts image.png to image.jpeg. You can also resize, rotate, flip, and query image properties.

To resize an image to a width of 800 pixels, maintaining aspect ratio:

sips -Z 800 image.jpg --out resized_image.jpg

This is incredibly useful for automating image workflows or quickly preparing images for web or specific applications.

Conclusion

The macOS Terminal is far more than just a programmer’s tool; it’s a powerful extension for anyone serious about mastering their Mac. The commands outlined above are just a glimpse into the vast capabilities available. From fine-tuning system behavior to performing advanced file operations and deep diagnostics, the command line offers an efficiency and level of control that the GUI often cannot match.

Embracing these “secret” commands can significantly enhance your productivity, allow for greater customization, and provide a deeper understanding of how your Mac truly operates. Remember the golden rule: always understand a command before you execute it, especially when using sudo. Start exploring, experimenting, and unlocking the full potential of your macOS system. The journey to becoming a true power user is an ongoing one, and the Terminal is your trusted companion on that path.

正文完
 0
评论(没有评论)
验证码