Mastering the macOS Command Line: Part 3

ElAmir Mansour
11 min readMay 3, 2024

--

In this chapter, you’ll explore navigating your Mac using the command line, learning some common commands and conventions along the way. But for now, it’s all about observation — no actions here can alter files or cause any harm, as long as you follow the instructions.

Discover Where You Are

Let’s start learning some commands. Open a Terminal window and type:

pwd

The pwd command, short for "print working directory," displays the complete path to your current directory. If you've just opened a Terminal window, this will typically show your home directory, like:

While this may seem mundane, it’s incredibly important for maintaining your bearings as you navigate through directories.

See What’s Here

In the Finder, you can visually assess what’s in the current folder. However, on the command line, you need to explicitly ask. Use the ls command to list the contents:

By default, this lists items alphabetically. To get more details, use the -l flag:

This provides a more comprehensive list, including file permissions, owner, size, and last modified date. But the size shown is in bytes, which isn’t always practical. To make it more readable, add the -h flag:

This will display sizes in a human-readable format, making it easier to interpret.

Making Output (More) Human-Readable

While ls is invaluable, starting in Catalina, it may not always show the complete picture. For instance, if you want to see macOS built-in apps, you'll need to specify their path:

Finally, you can quickly repeat previous commands using the arrow keys to navigate through your command history or by typing !!, which repeats the last command. This can save you time, especially with longer commands.

Cancel a Command

If you find yourself typing a command on the command line and suddenly realize you don’t want to execute it, there’s a quick way to back out. Simply press either Control-C or ⌘-. (period). This action creates a new blank command line, leaving your partially typed command unused. It's worth noting that canceled commands won't appear in your command history.

Move into Another Directory

You’ve explored your home directory, but now it’s time to venture further. To navigate into another directory, use the cd command. For example, to move into the "Library" directory within your home directory, type:

cd Library

Remember to use the correct case for directory names. If the directory doesn’t exist in your current location, you’ll receive an error message. Moving into a directory doesn’t automatically display its contents; you’ll need to use the ls command to see what's inside.

Move Up or Down

Once you’re in a directory, you can navigate further down by specifying its name after the cd command. To move up a level, use ... For example:

cd ..

This command moves you up one level in the directory hierarchy.

Move More Than One Level

You’re not limited to moving one level at a time. Use slashes to specify multiple levels at once. For instance:

cd Library/Preferences

This command navigates directly to the “Preferences” directory within the “Library” directory.

Move to an Exact Location

If you know the exact path to your destination, you can jump directly there using the full path starting with a slash (/). For instance:

cd /private

This command moves you to the “private” directory at the root level of your disk.

Move Between Two Directories

To return to the last directory you visited, use:

cd -

This command is handy for quickly switching between two directories.

Jump Home

To return to your home directory from anywhere on your system, simply type:

cd ~

Alternatively, typing cd without any arguments also takes you back home.

Understand How Paths Work

In the command-line environment, paths play a crucial role in navigating through directories. You’ve encountered both relative paths (like Library/Preferences, denoting the "Preferences" directory inside the "Library" directory within your current location) and absolute paths (such as /Library/Preferences, indicating the "Preferences" directory within the "Library" directory at the root level of your disk).

Spaces in Paths

Spaces in file or folder names can cause issues in the command line because spaces typically separate commands, flags, and arguments. To navigate to a directory with a space in its name, you have two options:

  1. Quotation marks: Enclose the entire path in double quotation marks. For example, cd "My Folder" would navigate to a directory named "My Folder".
  2. Escape the space: Place a backslash (\) before the space. For instance, cd My\ Folder achieves the same result.

Wildcards

Wildcards are special characters that represent one or more characters in a file or directory name. The two most commonly used wildcards are:

  1. * (asterisk): Represents zero or more characters. For example, cd App* would navigate to a directory whose name starts with "App".
  2. ? (question mark): Represents any single character. For instance, ls D? would list items in the current directory whose names start with "D" followed by a single character.

When using wildcards, be mindful of case sensitivity, especially in macOS, where file systems can be either case-sensitive or case-insensitive. Always use the correct case to ensure accurate navigation.

Understanding paths and how to handle spaces and wildcards can greatly enhance your efficiency and accuracy when working with the command line.

Understand the macOS Directory Structure

Your Mac’s directory structure might seem like a labyrinth at first glance, but you don’t need to understand every nook and cranny to navigate it effectively. Here’s what you should know:

  1. Visible and Invisible Folders: At the top level of your startup disk, you’ll find standard folders like Applications, Library, System, and Users. Each user’s home folder contains its own set of standard folders like Desktop, Documents, and Downloads. Additionally, macOS has numerous hidden directories that are typically invisible in the Finder but can be accessed from the command line.
  2. You Don’t Need to Know Everything: While understanding the intricate details of macOS directory structure might be useful for programmers or system administrators, it’s not necessary for everyday users. You don’t need to know why certain programs are stored in specific directories like /bin, /usr/bin, or /usr/local/bin. Instead, focus on following instructions when needed.
  3. Key Points to Understand:
  • The Invisible World of Unix: Running ls -l / in Terminal reveals all files and directories at the root level of your disk. Directories beginning with a lowercase letter (e.g., bin, dev, private) form the Unix core of macOS.
  • Recursion, Repetition, and Recursion: You’ll notice repetitive directory names as you navigate through your disk, such as /Library, /System/Library, and ~/Library. While the reasons behind these repetitions vary, it’s important to be in the right directory when working on the command line.
  • The Bandbox Rule: Avoid tinkering with critical system components if you’re unsure of the consequences. Just as you wouldn’t “monkey with the bandbox” for fear of breaking it irreparably, exercise caution when making changes in directories that could impact system stability.

Understanding these key points will help you navigate the macOS directory structure effectively without delving too deeply into its intricacies.

Use Tab Completion

Typing out long file and directory names repeatedly on the command line can be tedious and error-prone. Fortunately, zsh and bash shells offer a helpful feature called tab completion to reduce typing effort. Here’s how it works:

Basic Usage:

  • Start typing a file or directory name.
  • Press the Tab key.
  • If there’s only one matching item in the current directory, the shell completes the rest of its name.
  • If there are multiple matches, pressing Tab again displays a list of all matches.

Example:

  • If you’re in your home directory (cd), and you type cd De and press Tab, it might complete to cd Desktop/.
  • If there are multiple matches (e.g., Desktop/, Documents/, Downloads/), pressing Tab again shows all options.
  • You can continue typing more letters and pressing Tab to narrow down options until you find the desired one.

Beyond the Current Directory:

  • Tab completion isn’t limited to the current directory. You can use it to complete paths starting from any point.
  • For example, if you enter cd ~/Lib and press Tab, it might complete to cd ~/Library/.
  • You can keep adding more characters and pressing Tab to complete deeper directory paths.

Case Sensitivity:

  • Tab completion in zsh and bash is case-sensitive, even if the volume doesn’t use case-sensitive formatting.
  • For example, if a directory is named Widgets, typing wi and pressing Tab won't produce any matches if the casing doesn't match exactly.

By leveraging tab completion, you can significantly speed up your command line workflow and reduce the chances of typos or errors when navigating directories or entering file names.

Find a File

In the command-line environment, finding a particular file or directory can be accomplished using the find command. While it's comprehensive, traversing every directory in the specified area, it can be slow. Here's how to use it effectively:

Basic Usage:

  • Syntax: find [starting_directory] -name "[pattern]"
  • Example: find ~ -name "*keychain*"
  • Explanation:
  • find: Initiates the search.
  • [starting_directory]: Specifies the directory to start the search from.
  • -name "[pattern]": Searches for files or directories with names matching the specified pattern.

Tips for Usage:

  • Narrowing down the search range can speed up the process. For example:
  • To search only in ~/Library: find ~/Library -name "*keychain*"
  • To search the entire disk: find / -name "*keychain*"
  • To search in the current directory and all subdirectories: find . -name "*keychain*"

Case sensitivity:

  • By default, find is case-sensitive. To perform a case-insensitive search, replace -name with -iname.

Dealing with permission issues:

  • If find encounters directories you don’t have permission to search, it displays "Permission denied". To search these paths, use sudo before find.

Searching Contents of Files:

  • If you need to search the contents of files, consider using the grep command, although it usually takes longer than find.
  • See how to use grep in the section "Get a Grip on grep".

Using the find command allows you to locate files and directories based on various criteria, making it a powerful tool for managing your file system from the command line.

Locate

Another method for finding files by name is to use the locate command. Unlike find, which traverses every file, locate relies on a database (index) of file and path names. Here's how to use it effectively:

Basic Usage:

  • Syntax: locate [filename]
  • Example: locate keychain
  • Explanation:
  • locate: Initiates the search based on the database.
  • [filename]: Any portion of the filename you want to look for (no wildcards required).

Case Sensitivity:

  • By default, locate performs case-sensitive searches. To make a search case-insensitive, add the -i flag: locate -i keychain.

Database Update:

  • The database used by locate is typically updated only once a week. If you encounter errors indicating that the database doesn't exist or is outdated, you can update it using:
/usr/libexec/locate.updatedb
  • This command may take some time to complete, as it needs to index nearly every file on your disk.

Ownership:

  • By default, locate indexes and finds only files you own. This mainly includes the contents of your home directory.

Using the locate command can provide lightning-fast results for finding files by name. However, keep in mind that its effectiveness depends on the accuracy and currency of the underlying database.

View a Text File

Reading text files is a common task in the command-line environment for various purposes such as examining configurations, viewing scripts, and inspecting logs. Here are some commands you can use to view text files:

More or Less:

  • more and less are Unix programs for reading text files, with less being an enhanced version of more.
  • Both more and less allow you to scroll through the file.
  • Syntax:
less /path/to/file
more /path/to/file
  • To navigate:
  • ↓: Scroll down a line
  • ↑: Scroll up a line
  • Spacebar: Scroll down a screen
  • B: Scroll up a screen
  • To quit less: Press Q.

Cat:

  • The cat command (short for "concatenate") can display the entire contents of a text file.
  • Unlike less, it doesn't provide a paged view.
  • Syntax:
cat /path/to/file

Tail:

  • tail displays the tail end of a file, which is useful for viewing logs or the end of long files.
  • By default, it shows the last 10 lines of the file.
  • Syntax:
tail /path/to/file

To specify the number of lines:

tail -n [number] /path/to/file

Head:

  • head displays the beginning of a file, typically the first 10 lines.
  • Syntax:
head /path/to/file

To specify the number of lines:

head -n [number] /path/to/file

These commands provide different ways to view the contents of a text file in the terminal, allowing you to choose the method that best suits your needs.

Get Help

When you’re working on the command line and need information about a specific command, you can access its documentation using the man command, short for "manual." Here's how:

Using man Command:

man [command]

for example :

man ls
man cp
man locate

This command displays the manual pages for the specified command in a viewer similar to less.

Using Terminal’s Help Menu:

  • You can also access command documentation through Terminal’s Help menu:
  • Click Terminal’s Help menu.
  • Type the name of the command in the Search field.
  • Select the desired command from the results and press Return.

Alternatively, right-click (or Control-click) on the command in the Terminal window and choose “Open man Page” from the contextual menu.

  • If your cursor is immediately to the right of the command, press ⌘-Control-? to view its man page.

Reading Man Pages as PDF:

  • If you prefer nicely formatted PDF files, you can use a recipe like “Read man Pages in Preview.”

Using Bwana App:

  • You can read your Mac’s man pages in your web browser using the free Bwana app.

Clear the Screen

To clear the clutter in your Terminal window and focus on the command line, you can use the following methods:

  • Enter clear or press Control-L to clear the window and move the command line to the top.
  • To clear the screen and prevent someone from scrolling back, press ⌘-K, which has the same effect as opening a new Terminal window.

End a Shell Session

When you’re done working in Terminal, use the exit command to gracefully end the shell session. This command stops any running programs in the shell and quits the shell itself. When the command completes, you'll see [Process completed], indicating that the shell has fully exited.

If you found this blog helpful or have any questions, feel free to reach out to me on social media:

--

--

ElAmir Mansour

🚀 Software Engineer & iOS Developer | Scrum Master 🕹 | Crafting Code & Content | Coffee enthusiast ☕️ | Simplifying Complexity, One Line at a Time 💻