Lesson 4

Use the Command-Line Interface

Goals

  • images Describe when the command-line (CLI) interface is useful

  • images Use man (manual) pages to find more information about commands

  • images Manipulate files in the CLI

  • images Use the CLI to access additional administrative functionality

Reference 4.1 CLI Basics

The CLI includes these advantages beyond what is available in the GUI:

  • images Additional administrative and troubleshooting options are available from the CLI. For example, the following apps have CLI equivalents that include additional options: System Information (system_profiler), Installer (installer), Software Update (softwareupdate), Disk Utility (diskutil), and Spotlight (mdfind). These are just a few examples. You can accomplish many administrative tasks either by using an app or by using a command in Terminal. Being familiar with the CLI will allow you to choose the most effective way to accomplish a task.

  • images From the CLI you have more access to the file system. For example, the Finder hides many files and folders that are visible in the CLI. Also, the Finder doesn’t display all the file-system permissions settings.

  • images You can remotely log in to a Mac computer’s CLI using the Secure Shell (SSH) protocol. The next section contains more information about SSH.

  • images By using the sudo command, any administrator can run commands as the System Administrator user, also known as root. This enables greater administrative flexibility in the CLI. Reference 7.1, “User Accounts,” provides more information about the root account.

  • images If you are comfortable with the CLI syntax, you can apply it to a command-line script. Doing so enables you to automate repetitive tasks.

  • images By combining CLI instructions with Apple Remote Desktop (ARD), you can remotely administer multiple, even thousands, of Mac computers simultaneously. ARD enables you to remotely send the same command to several Mac computers with one click. For more information about Apple Remote Desktop refer to the Apple Remote Desktop User Guide at support.apple.com/guide/remote-desktop/.

Access the CLI

A shell is a program that creates an interface to command a computer operating system. In macOS Monterey the default shell used for the CLI is Z Shell (zsh) and it displays the CLI. You can access the CLI in several ways:

  • images You can use Terminal. It’s in /Applications/Utilities/. Terminal has a customizable interface that includes tabs for multiple command-line sessions, multiple split panes for viewing history, support for full-screen mode, and Touch Bar shortcuts.

    Images

    You can customize Terminal window settings, such as typeface, color, background, and other settings. A Terminal profile is a collection of style and behavior settings. Open Terminal preferences, then select Profiles in the toolbar. Select a preexisting profile or create new profiles to match your needs. If you use multiple Terminal windows, you can use different profiles to help ensure you are working in the appropriate window.

    Images

    After you modify or create a new profile, click Default next to the Action menu. The next time you open a new Terminal window, it will use this profile.

  • images Start in macOS Recovery to open Terminal from the Utilities menu.

  • images Single-user mode is available for a Mac with the Apple T2 Security Chip if you configure the Secure Boot setting to No Security. This mode starts the minimum system required to provide you with a command-line prompt so that you can enter commands to troubleshoot a Mac that can’t fully start up. Single-user mode lessens the security of your Mac. If you turn on single-user mode to accomplish a task, return your Mac to Full Security when the task is complete. Learn more about single-user mode in Lesson 28, “Troubleshoot Startup and System Issues.”

  • images SSH remote login enables you to securely log in from a remote computer to access your Mac computer’s command line. SSH is a common standard, so you can use any operating system that supports SSH to remotely log in to your Mac. This remote access allows administrators to make changes at the command line without interrupting or alerting a user to their work. Before you can use SSH to connect to your Mac, you must turn on SSH access.

    Warning

    Because SSH remote login lessens the security of your Mac, if you turn on SSH remote login to accomplish a task, turn off SSH remote login after you complete your task.

Work in the Command Line

When you first open Terminal, it may display information about your last login. Then it will display the prompt.

Images

The prompt indicates that you can enter a command. By default, the prompt shows you the following:

  • images Your current user account name

  • images The @ symbol

  • images The name of the Mac you’re using

  • images Your location in the file system

  • images A special character that provides a hint about which shell you’re using

macOS Monterey uses the Z shell (zsh) by default, but if you upgraded your Mac from a version earlier than macOS Catalina, you might still be using the bash shell:

  • images zsh uses % at the end of the prompt.

  • images bash uses $ at the end of the prompt.

Refer to Apple Support article HT208050, “Use zsh as the default shell on your Mac,” for more information about different shells, including instructions about script compatibility.

Where you are in the computer’s file system is called the working directory, and it changes as you navigate through the file system.

At the prompt, you enter your command string, often more than one word, and press Return to initiate or execute the command.

An executing command takes over the Terminal window with a text interface, shows the results of the command, and returns to the prompt, or it performs some work and returns to the prompt when complete. Many commands display results only if a problem occurs. Review what the command returns to make sure it doesn’t indicate a problem.

Images

Some commands take time to execute and may not give a progress indication. If a new prompt does not appear, generally assume your last command is still running.

When you use Terminal to access some files and folders on your Mac for the first time, macOS asks for your explicit approval. These files and folders include portions of your home folder and removable volumes.

Images

You’ll see the results of your privacy decisions in the Privacy pane of the Security & Privacy preferences in System Preferences.

When you grant Terminal access, you lessen security on your Mac. You can remove the ability for Terminal to access files and folders after you complete the task that requires access. Check out Reference 9.5, “Manage User Privacy,” for more information. The following figure shows that the logged-in user has granted Terminal permission to access three critical areas. The user can unlock the System Preference pane and deselect the checkboxes to remove access for Terminal.

Images
Command String

The command string includes a few parts:

Images
  • images Command name (1)—Some commands just need you to enter their name to execute.

  • images Options (2)—After a command name, you might specify options (or flags) that change a command’s default behavior. Options might not be required and can be different for every command. Options start with one or two dashes to distinguish them from arguments. Many commands can include several single-letter options after a single dash. For example, ls -lA is the same as ls -l -A.

  • images Arguments (3)—After the command and its options, you typically specify an argument (or parameter), which is the item or items you want the command to modify. An argument is needed only if the command requires an item to act upon and if that item can’t be logically inferred from the working directory.

  • images Extras (4)—Extras aren’t necessary, but they can enhance the capabilities of a command. For example, you could add items that redirect the command output, include other commands, or generate a document.

Command-Line Example

Here is an example in which the user Karina works on a Mac called Karina’s MacBook Pro and her working directory is her Public folder. She deletes a file called list.txt. Karina presses Return after she enters her command.

karina@Karinas-MacBook-Pro Public % rm list.txt

karina@Karinas-MacBook-Pro Public %

In this example the command was entered and executed properly, and macOS returns to a new prompt. This is an example of a command that returns information only if it didn’t execute properly. The CLI usually lets you know if you entered something incorrectly by returning an error message or help text. macOS won’t prevent or warn you from entering a destructive command, such as accidentally deleting files in your home folder. Always double-check your typing.

Use Manual (man) Pages

When you want to learn more about a command, you type man followed by the name of the command. Manual (man) pages include detailed information about commands and references to other commands. After you open a man page, use navigation shortcuts to move through it:

  • images Use the Up Arrow and Down Arrow keys to scroll.

  • images Use the Space bar to move down one screen at a time.

  • images Enter a slash (/), enter a keyword, then press Return to search through a man page.

  • images Exit the man page by typing q.

Manual (man) Pages Structure

The items described in the manual are grouped into eight sections that correspond to the kinds of functions the items perform. The number that appears in the man page next to the name of the command corresponds to the section in which the command appears.

Individual man pages have a defined structure, but you will find that not every command’s man page is fully documented. The elements of a man page are as follows:

  • images The NAME section includes the command’s name and a terse description of the command’s function.

  • images The SYNOPSIS includes a formal description of how to run the command, followed by the options the command takes.

  • images The DESCRIPTION provides a more detailed description of the function of the command as well as the options available and their use.

  • images EXAMPLES can show intended use and options; however, this section is not always present.

  • images SEE ALSO directs you to similar commands or commands that can perform a related function.

  • images Additional elements may include: OPTIONS, EXIT STATUS, RETURN VALUE, ENVIRONMENT, BUGS, FILES, AUTHOR, REPORTING BUGS, HISTORY, and COPYRIGHT.

    Images

Reference 4.2 CLI Navigation

The command line is case-sensitive and requires that you use full filenames with filename extensions. For example, unless you specify to ignore case, the CLI won’t locate the “music” app, but it will locate the “Music.app” app.

A path, or pathname, represents a file or folder’s location in the file system. For instance, Launch daemons are stored in a folder whose file-system pathname is /Library/LaunchDaemons/. Path is a less formal term used when describing the location of a file in a folder hierarchy, but a pathname will use the standard syntax of [parent folder]/[subfolder]. In the CLI, you use the pathname to navigate the file system and to identify the location of items. Reference 15.1, “macOS File Resources,” provides more information on launch daemons.

There are two types of file-system pathnames:

  • images Absolute paths are full descriptions of an item location, starting from the root (or beginning) of the system (startup) volume. An absolute path begins with a forward slash (/) to indicate the beginning of the file system. An example of the absolute path to the user Karina’s drop box folder is /Users/karina/Public/Drop Box, which means: Start from the startup volume; go to the Users folder, then the karina subfolder, then the Public subfolder; and select the item named Drop Box.

  • images Relative paths are partial descriptions of an item location. They’re based on where you’re currently working in the file system. When you first open Terminal, your session starts at your home folder. The relative path from your home folder to your drop box is Public/Drop Box. This means: From where you are now, go into the Public subfolder and select the item named Drop Box.

Navigate with Commands

You can drag and drop items from the Finder to Terminal. When you do this, Terminal enters an item’s absolute path with the appropriate backslash characters before spaces in names. Use the Tab key completion feature that’s built into the command line to automatically complete filenames and pathnames.

If you can’t or don’t want to drag and drop items from the Finder into Terminal, you can navigate using three main commands: pwd, ls, and cd. Short for “print working directory,” pwd reports the absolute path of your current working location:

karina@Karinas-MacBook-Pro ~ % pwd

/Users/karina

Short for “list,” ls lists the folder contents of your current working location. Enter a pathname following the ls command to list the contents of the specified item. The ls command has additional options for listing file and folder information that are covered throughout this lesson.

Short for “change directory,” cd is the command you use to navigate. Enter a pathname following the cd command to change your current working location to the specified folder. Entering cd without specifying a path returns you to your home folder.

Use Special Characters

You can use special characters with unique meanings in the CLI at the prompt or in pathnames to save time. You will use special characters to indicate to the CLI when special characters appear in filenames and pathnames. Doing so ensures that the CLI can properly understand how to interpret the use of these characters.

Enter a space between command items to separate the items. If you don’t want the space character to separate items, use the backslash () before a space character.

karina@Karinas-MacBook-Pro ~ % cd Public/Drop Box

karina@Karinas-MacBook-Pro Drop Box % pwd

/Users/karina/Public/Drop Box

Another way to enter filenames and paths with spaces is to surround filenames and paths with quotation marks:

karina@Karinas-MacBook-Pro ~ % cd "Public/Drop Box"

karina@Karinas-MacBook-Pro Drop Box % pwd

/Users/karina/Public/Drop Box

Other special characters are !, $, &, *, ;, |, , parentheses, quotes, and brackets. The Finder drag-and-drop and Tab key completion parse these characters. In the CLI you can enter a backslash before any special character to treat that special character as regular text rather than as a special character.

Use double periods (..) to indicate a parent folder. For example, if you are in your home folder at /Users/username, type cd .. to navigate to the /Users folder.

Use the tilde (~) to indicate the current user’s home folder in a pathname. For example, if the current user’s working directory is /Applications and they wish to list the contents of their Documents folder, you can use the tilde to indicate the user’s home folder: ls ~/Documents.

Use Tab Key Completion

Use Tab key completion to automatically complete filenames, pathnames, and command names. Tab key completion prevents you from making typos and verifies that the item you’re entering exists.

Here’s an example of Tab key completion. Start from your home folder by typing cd, then P, and then press the Tab key. The Terminal window flashes quickly, and you may hear an audible alert, letting you know there is more than one choice for items that begin with “P” in your home folder. Press the Tab key again, and the Mac displays your two choices, Pictures and Public. Now, type u after the initial P, and then press the Tab key again, and the Mac automatically finishes Public/ for you. Type D and press the Tab key one last time, and the Mac finishes the path with Public/Drop Box/.

When completing a folder name, Tab key completion puts a forward slash (/) at the end. It assumes that you want to continue the path. Most commands ignore the trailing slash, but a few behave differently if it’s there. If in doubt, you should delete the / at the end of a path.

Tab key completion reads only into folders you have permission to access. You may run into issues trying to use this feature for items that are readable only by the root user.

View Invisible Items

The CLI and the Finder hide many files and folders from view. The hidden items are often created and used by macOS. In the Finder, these items are set with a hidden file flag. The CLI ignores the hidden file flag and shows most hidden items. If you type the ls command, filenames that begin with a period won’t appear. To see hidden items in long format at the command line, add the -a option to the -l option when you enter the ls command:

karina@Karinas-MacBook-Pro ~ % ls -la /Users
total 0
drwxr-xr-x           8 root         admin       256  Aug 25   13:29   .
drwxr-xr-x          22 root         admin       704 Aug 20   22:57   ..
-rw-r--r--               1 root         wheel         0      Jul 14   15:30   .localized
drwxrwxrwt         6 root         wheel       192   Aug 21   10:59   Shared
drwxr-xr-x+       11 john         staff       533     Aug 25   13:23   john
drwxr-xr-x+       11 karina       staff       352   Aug 25   13:29   karina

Any item with a period at the beginning of its name is hidden by default in the CLI and the Finder.

Navigate to Other Volumes

The CLI uses a concept called firm links, explained in Reference 11.1, “File Systems,” to present both the read-only APFS System volume and the read-write APFS Data volume as if they were a single volume, known as the root volume. The root volume is identified by a lone forward slash. Other nonroot volumes appear as part of the main file system in the Volumes folder at the root of the startup disk.

Use Marks and Bookmarks

Add marks and bookmarks as you work, then use them to quickly navigate through lengthy Terminal output.

Select a line in Terminal, then choose Edit > Marks > Mark to add a mark. By default, Edit > Marks > Automatically Mark Prompt Lines is selected, so each prompt line sets a mark. Then you can choose Edit > Select Between Marks or choose Edit > Navigate > Jump to Previous Mark, or just press Command-Up Arrow.

Choose Edit > Marks > Mark as Bookmark to add a bookmark. Then choose Edit > Bookmarks to display a list of bookmarks. Choose one to jump to that bookmark.

Reference 4.3 Manipulate Files in the CLI

When you manage and edit files in the CLI, you have more options—and more chances to make mistakes.

File Examination Commands

Use the cat, less, and file commands to examine files. Review the man pages for these commands to find out more about them.

Short for concatenate, the cat command displays the contents of a file sequentially to Terminal. The syntax is cat, followed by the path to the item you want to view. Use the cat command to append to text files using the >> redirect operator. In the following example, Karina uses the cat command to view the content of two text files in her Public folder, TextDocOne.txt and TextDocTwo.txt. Then she uses the cat command with the >> redirect operator to append the second text file to the end of the first text file.

karina@Karinas-MacBook-Pro ~ % cat Public/TextDocOne.txt

This is the content of the first plain text document.

karina@Karinas-MacBook-Pro ~ % cat Public/TextDocTwo.txt

This is the content of the second plain text document.

karina@Karinas-MacBook-Pro ~ % cat Public/TextDocTwo.txt >> Public/TextDocOne.txt

karina@Karinas-MacBook-Pro ~ % cat Public/TextDocOne.txt

This is the content of the first plain text document.

This is the content of the second plain text document.

Use the less command to view long text files. It enables you to browse and search the text. Type less, followed by the path to the item you want to view. The less interface is the same interface you use to view man pages, so the navigation shortcuts are the same.

The file command determines a file type based on its content. This is useful for identifying files that don’t have a filename extension. The syntax is file, followed by the path to the file you’re trying to identify. In the following example, Karina uses the file command to locate the file type of two documents in her Public folder: PictureDocument and TextDocument:

karina@Karinas-MacBook-Pro ~ % file Public/PictureDocument.jpeg

Public/PictureDocument.jpeg: JPEG image data, JFIF standard 1.01, resolution (DPI),
density 300x300, segment length 20, Exif Standard: [TIFF image data, big-endian, direntries=13,
manufacturer=Apple, model=iPhone 12 Pro Max, orientation=upper-left, xresolution=194,
yresolution=202, resolutionunit=2, software=14.7, datetime=2021:08:03 17:20:46,
hostcomputer=iPhone 12 Pro Max], baseline, precision 8, 2176x3869, components 3

karina@Karinas-MacBook-Pro ~ % file Public/TextDocument.txt

Public/TextDocument.txt: ASCII text, with very long lines (438)

To use Spotlight from the command line, enter the mdfind command. The syntax is mdfind, followed by your search criteria. Like Spotlight, mdfind returns only items that the current user has permissions to access. Reference 16.2, “Siri and Spotlight” has more information.

Use Wildcard Characters

You can use wildcard characters to define pathname and search criteria. Here are three of the most common wildcards:

  • images Use the asterisk (*) wildcard to match any string of characters. For instance, entering * matches all files, and entering *.tiff matches all files that end in .tiff.

  • images Use the question mark (?) wildcard to match a single character. For example, entering b?ok matches book but not brook.

  • images Use square brackets ([ ]) to define a range of characters. For example, [Dd]ocument locates items named Document or document, and doc[1-9] matches files named doc#, where # is a number between 1 and 9.

You can combine filename wildcards. Consider a collection of five files with the names ReadMe.rtf, ReadMe.txt, read.rtf, read.txt, and It’s All About Me.rtf. Using wildcards to specify these files:

  • images *.rtf matches ReadMe.rtf, read.rtf, and It’s All About Me.rtf.

  • images ????.* matches read.rtf and read.txt.

  • images [Rr]*.rtf matches ReadMe.rtf and read.rtf.

  • images [A-Z]*.* matches ReadMe.rtf, ReadMe.txt, and It’s All About Me.rtf.

Use Recursive Commands

When you direct a command to execute a task on an item, it acts on only the item you specify. If the item you specify is a folder, the command won’t navigate inside the folder to execute the command on the enclosed items. If you want a command to execute on a folder and its contents, you must tell the command to run recursively. Recursive means: Execute the task on every item inside every folder starting from the path I specify. Many commands accept -r or -R as the option to indicate that you want the command to run recursively.

Modify Files and Folders

The mkdir, touch, cp, mv, rm, rmdir, and nano commands enable you to modify files and folders.

Short for “make directory,” mkdir is used to create folders. The syntax is mkdir, followed by the paths of the folders you want to create. The -p option tells mkdir to create intermediate folders if they don’t already exist in the paths you specify.

Use the touch command to update the modification date of a specified item. The touch command creates an empty file if it doesn’t exist.

Use the cp (copy) command to copy items from one place to another. The syntax is cp, followed by the path to the original item, ending with the destination path for the copy. If you specify a destination folder but no filename, cp makes a copy of the file with the same name as the original. If you specify a destination filename but not a destination folder, cp makes a copy in your current working folder. Unlike the Finder, the cp command won’t warn you if your copy replaces an existing file. It deletes the existing file and replaces it with the copy you told it to create.

Use the mv (move) command to move items from one place to another. The syntax is mv, followed by the path to the original item, ending with the new destination path for the item. You can also use mv to rename an item. The mv command uses the same destination rules as the cp command.

Use the rm (remove) command to permanently delete items. There is no Trash in the CLI. The rm command removes items forever. The syntax is rm, followed by the paths of the items you wish to delete.

Use rmdir (remove directory) to permanently delete folders. The rmdir command removes folders forever. The syntax is rmdir, followed by the paths of the folders you want to delete. The rmdir command can remove a folder only if it’s empty. You can use the rm command with the recursive option, -R, to remove a folder and all its contents.

The text editor nano features a list of commonly used keyboard shortcut commands at the bottom of the screen. There’s an illustration of using the nano command in Exercise 4.2, “Manage Files and Folders with Commands.

Reference 4.4 Manage macOS from the CLI

In this section, you look at commands that enable you to access items normally restricted by file-system permissions.

Use the su (substitute user identity or super user) command to switch to another user account. Type su, followed by the short name of the user you want to switch to, and enter the account password. The password won’t display. The command prompt changes, indicating that you have the access privileges of a different user. Type who -m to verify your currently logged-in identity. You remain logged in as the substitute user until you quit Terminal or enter the exit command. In the following example, Karina uses the su command to change her shell to John’s account, and then she will exit back to her account:

karina@Karinas-MacBook-Pro ~ % who -m

karina ttys001 Aug 20 14:06

karina@Karinas-MacBook-Pro ~ % su john

Password:

john@Karinas-MacBook-Pro ~ % who -m

john ttys001 Aug 20 14:06

john@Karinas-MacBook-Pro ~ % exit

exit

karina@Karinas-MacBook-Pro ~ % who -m

karina ttys001 Aug 20 14:06

Use sudo

Precede a command with sudo (substitute user do) to tell macOS to run the command using root account access. You must have an administrator user account to use sudo. sudo works even when the root user account is disabled in the graphical interface. Be careful with sudo and limit access to it.

System Integrity Protection (SIP) prevents changes to parts of macOS, even for the root user. Reference 15.2, “System Integrity Protection,” contains more information about the specific resources that are protected.

If, as an administrator user, you need to execute more than one command with root account access, you can temporarily switch the entire command-line shell to have root-level access. Type sudo -s and your password to switch the shell to root access. You remain logged in as the root user until you quit Terminal or enter the exit command.

Learn more about the root account in Reference 7.1, “User Accounts.

Warning

Do not enable the root user account for daily use. Its privileges allow you to make changes that you can undo only by reinstalling macOS. If you need to enable the root user account (instead of just using the sudo command), be sure to disable the root user account after you complete your task.

Reference 4.5 Command-Line Tips and Tricks

Here are some command-line tips that help you customize your experience and save time:

  • images Control-click a command and choose “Open man Page” to learn more about that command.

    Images
  • images If your Mac has a Touch Bar, type a command and press the button for that command in the Touch Bar to open a new Terminal window that displays the man page for the command. The figure shows the Touch Bar displaying a button for the xattr command man page.

    Images
  • images Use Tab key completion when you enter file paths.

  • images Type open . (“open” followed by a space, followed by a period) at the prompt to open your current command-line location in the Finder.

  • images Explore Terminal preferences (from the menu bar, choose Terminal > Preferences, or press Command-Comma) to customize the look and feel of your command line.

  • images To cancel a command or clear your current command entry, use Control-C.

  • images You can edit commands before submitting. The Left and Right Arrow keys and the Delete key work as you would expect.

  • images At the command prompt, use the Up Arrow and Down Arrow keys to view and reuse your command history. This includes editing old commands before rerunning them. Enter the history command to display your recent command history.

  • images To clear the Terminal screen, enter the clear command or press Control-L.

  • images To move the cursor to the beginning of the current line, press Control-A.

  • images To move the cursor to the end of the current line, press Control-E.

  • images To move the cursor forward one word, press Esc-F.

  • images To move the cursor back one word of the line, press Esc-B.

  • images To move the cursor to a location in a command string, Option-click where you’d like the cursor to be.

  • images Use the inspector to view and manage running processes as well as edit window titles and background colors. To open the inspector, press Command-I. To send a command to a process, select it, click the Action menu, then choose a command from the Signal Process Group.

You can find more information about Terminal in the Terminal User Guide at support.apple.com/guide/terminal/.

Exercise 4.1 Command-Line Navigation

In this exercise, you use commands in Terminal to navigate the file system, to view items that aren’t visible from the Finder, and to access the manual (man) pages that tell you about commands.

View Your Home Folder

  1. If necessary, log in to your Mac as Local Administrator.

  2. Click Launchpad in the Dock.

    Images
  3. In the Search field at the top of the screen, type Terminal.

  4. Click Terminal.

    A new Terminal window opens.

    Images

    The second line includes your user name and computer name followed by a prompt—for example:

    ladmin@Mac-17 ~ %

    In this example, the user named ladmin is logged into a computer named Mac-17. A space separates the computer name from the path to your current working directory, which is ladmin’s home folder, indicated by the tilde (~). The path is followed by the prompt, which is %.

  5. At the prompt, type ls and press Return.

    Terminal displays output that looks something like this, followed by another prompt:

    Desktop    Downloads  Movies     Pictures
    Documents  Library    Music      Public
    
  6. Switch to the Finder. If you don’t find an open Finder window, choose File > New Finder Window or press Command-N.

  7. Select ladmin’s home folder in the Finder sidebar and compare the contents of the home folder in the Finder and Terminal.

    With the exception of the Library folder, what you see in Terminal is the same as in the Finder. (User Library folders are hidden in the Finder by default; see Reference 14.1, “Examine Hidden Items.”)

  8. Switch back to Terminal and type ls -A (lowercase LS followed by space, a hyphen, and an uppercase A) at the prompt and press Return.

    In general, the command-line environment is case-sensitive. For example, ls -a isn’t the same as ls -A.

    The list includes some additional files that begin with a period. Files beginning with a period are hidden in directory listings unless you ask for them by typing ls -A. The Finder doesn’t show files beginning with a period (sometimes called dot-files).

Examine and Change Your Current Working Directory

Think of your current working directory as the place where you are in the file system. When you open a new Terminal window, your default working directory is your home folder. Use the cd command to change your current working directory.

  1. At the prompt, type pwd.

    The period (.) ends the sentence and isn’t part of the command, so don’t type it. This guide tells you if a trailing “.” is part of the command. Also, press Return at the end of each step unless otherwise instructed.

    Terminal displays:

    /Users/ladmin

    This is where Local Administrator’s home folder exists in the file system. It’s the folder you’re “in” in this Terminal window.

  2. At the prompt, type cd Library.

    This changes your current working directory to the Library folder inside your home folder.

    This command uses a relative path. A relative path means “Start in my current working directory.”

    Your prompt changes to something like this:

    ladmin@Mac-17 Library %

    The path component of the prompt indicates the folder you are in, not the entire path.

    The cd command changed your working directory without providing feedback. A command that completes and doesn’t need to provide feedback will exit silently. If you get an error message, you should investigate its cause before continuing.

  3. At the prompt, type pwd. Terminal displays:

    /Users/ladmin/Library

    You changed to the Library folder that was inside your previous working directory.

  4. Type ls to view what files and folders are in this Library folder.

  5. At the prompt, type cd /Library. Note the / that precedes Library this time.

  6. At the prompt, type pwd. Terminal displays output like this:

    /Library

    This is a different folder.

    A path that starts with a leading / is an absolute path. It means “Start at the root folder and navigate from there.” A path that doesn’t start with a leading / is a relative path. It means “Start in your current working directory and navigate from there.” (For more information on file system structure, refer to Reference 15.1, “macOS File Resources.”)

  7. Type ls to view the files and folders that are in this Library folder.

    There is some overlap in the item names in this Library and the one in ladmin’s home folder, but the names aren’t entirely the same.

  8. At the prompt, type cd and a space character. Don’t press the Return key.

    Terminal enables you to drag and drop items from the Finder to Terminal and have the path to the items appear in the command line.

    In this part of the exercise, you use the Finder to locate a folder you want to use as your working directory in Terminal.

  9. Switch to the Finder.

    When you don’t know exactly what you are looking for, it’s sometimes faster and easier to find a file or folder in the Finder.

  10. Open a new Finder window if necessary.

  11. Click Macintosh HD in the sidebar.

  12. Open the Users folder.

  13. Drag and drop the Shared folder to Terminal.

    Terminal fills in the path (/Users/Shared). Macintosh HD doesn’t appear in the path that Terminal fills in.

    The Finder shows you volume names to make locating a particular volume easier. Terminal doesn’t show volume names in the same way.

  14. Switch to Terminal and press Return.

    You are in the Shared folder.

  15. Type pwd at the prompt.

Read About ls in the Man Pages

In Terminal, you can read the details about commands using the man command. man is short for manual.

  1. In Terminal, type clear, then press Return.

    The clear command moves all the text in the command-line interface one page up.

  2. At the prompt, type man ls, then press Return.

    This opens the man page for the ls command.

    Man pages and their various parts give you guidance on how to use commands in the command-line interface. For more information on man pages, refer to Reference 4.1, “CLI Basics.

  3. Type q to quit viewing the man page for ls.

  4. At the prompt, type man man, then press Return.

    You can also Control-click a command in the Terminal to open its man page. On a MacBook Pro with Touch Bar, if the insertion point is in a command, you can tap the name of the command in the Touch Bar to open its man page.

  5. Read about the man command.

  6. When you are done, type q to exit.

Exercise 4.2 Manage Files and Folders with Commands

In this exercise, you learn to copy, move, rename, and delete files and folders with commands.

Create Files

  1. If necessary, authenticate as Local Administrator.

  2. Open TextEdit.

    TextEdit should be in your Dock from when you performed Exercise 3.3, “Download Student Materials.” If it isn’t in your Dock, you can find it in /Applications.

  3. Do one of the following:

    • images If the file navigation dialog opens, click the New Document button.

    • images Choose File > New.

  4. In the TextEdit menu bar, choose Format > Make Plain Text, or press Shift-Command-T.

  5. Add the following names to the yet Untitled (default) TextEdit document:

    MacBook Air

    MacBook Pro

    iMac

    iMac Pro

    Mac Pro

    Mac mini

    iPhone

    iPad

    Images
  6. From the TextEdit menu bar, choose File > Save and name the document Comps.

    Accept the default location and click Save to save the file in the Documents folder.

    Images
  7. Close the Comps document window.

  8. Create a new document in TextEdit and change the format to Plain Text.

  9. Save the file in the default location (the Documents folder) and name the new document Empty.

  10. Quit TextEdit.

Copy and Move Files and Create a Folder

  1. In the Finder, open your Documents folder.

  2. If necessary, open Terminal. Select Edit > Clear to Start (Command-K) to clear your Terminal window.

    Unlike the clear command used here, the Clear to Start command is unique to the Terminal app and does not save any output.

  3. Arrange the Finder window showing the Documents folder and the Terminal window so that you can see most of both windows on the screen.

    You will observe how commands that you run in Terminal affect the Finder.

  4. Type cd ~/Documents to change to the Documents folder.

    Images
  5. Type ls to view the files in the Documents folder.

    A dialog appears requesting that you allow Terminal to access files in your Documents folder.

    Note

    To protect your data, macOS has strict privacy preferences that prevent apps from accessing other apps’ data (commonly referred to as cross-app data access). Allowing access to your Documents folder lessens the security of your Mac. For the purposes of this exercise, you will allow access and then disallow access at the end. In production, when you see these prompts, understand what you are allowing before you click OK. If the dialog mentioned in step 5 doesn’t appear, you’ll need to grant Terminal access to your files and folders in the Security & Privacy pane of System Preferences. All of these topics are covered in Reference 9.5, “Manage User Privacy,” and in Exercise 9.2, “Allow Apps to Access Your Data.

  6. Click OK.

    View the output (also called stdout, or standard output) of the ls command. When you save a plain-text file from TextEdit, the program adds the filename extension .txt to it.

  7. Use cp to make a copy of Comps.txt and rename it MacModels.txt.

    ladmin@Mac-17 Documents % cp Comps.txt MacModels.txt

    Many commands that take a source and a destination list the source first.

  8. Use less with the complete filename to view each file, then type q to exit each file.

    MacModels.txt is an exact copy of Comps.txt.

    ladmin@Mac-17 Documents % less MacModels.txt

  9. Type q to exit.

  10. Enter the same command for the file Comps.txt:

    ladmin@Mac-17 Documents % Mac-17:Documents ladmin$ less Comps.txt

  11. When you are done, type q to exit.

Create a Folder and Copy a File to It

  1. Create a new folder in the Documents folder:

    ladmin@Mac-17 Documents % mkdir AppleInfo

    Because AppleInfo is a relative path, the folder is created in the Documents folder.

  2. Use cp to copy MacModels.txt into AppleInfo. You can press the Tab key after typing the first few characters to use Tab key completion to fill in the rest of the filename. This makes entering text in the command-line interface more efficient and accurate:

    ladmin@Mac-17 Documents % cp MacModels.txt AppleInfo

    Note

    Tab key completion often adds a trailing / (forward slash) at the end of a command. This exercise produces the same result whether or not the trailing / is present.

  3. Type ls to view the contents of AppleInfo:

    ladmin@Mac-17 Documents % ls AppleInfo

Fix a Naming Error

The text list in MacModels.txt includes a couple of items that are not technically Mac computers. Let’s rename the file and clean up the extra copies.

  1. Remove the Comps.txt file from the Documents folder and the MacModels.txt file from the AppleInfo folder:

    ladmin@Mac-17 Documents % rm Comps.txt AppleInfo/MacModels.txt

    You entered the command once to delete both files. The command line doesn’t have an undo function. Any change you make is permanent.

  2. Move the MacModels.txt file into the AppleInfo folder using the mv command:

    ladmin@Mac-17 Documents % mv MacModels.txt AppleInfo

  3. Type cd AppleInfo to change your working directory to AppleInfo.

  4. Use mv to rename the MacModels.txt file to AppleHardware.txt.

    ladmin@Mac-17 AppleInfo % mv MacModels.txt AppleHardware.txt

    Alternatively, you can also move and rename a file in one command:

    % mv MacModels.txt AppleInfo/AppleHardware.txt

Remove a Folder

  1. Change your working directory back to the Documents folder. You can do so in one of three ways:

    • images Use the absolute path /Users/ladmin/Documents.

    • images Use the tilde character to navigate to your home folder, ~/Documents.

    • images Use the relative path (..).

    The .. notation refers to the parent directory of the current directory. Because your current working directory is /Users/ladmin/Documents/AppleInfo, .. refers to /Users/ladmin/Documents.

    Occasionally, you see the .. notation in the middle of a path instead of at the beginning—for example, /Users/ladmin/Documents/../Desktop. It still has the same meaning, so in this example, it refers to Local Administrator’s Desktop folder.

    Similarly, a single . refers to the current directory or location in the path.

    Each directory contains a reference to both itself and its parent. These are visible if you use ls -a (note the lowercase a instead of the uppercase A you used previously).

  2. Move the AppleHardware.txt file to Documents and rename it AppleHardwareInfo.txt.

    Don’t press the Return key until you type AppleHardwareInfo.txt.

    ladmin@Mac-17 Documents % mv AppleInfo/AppleHardware.txt AppleHardwareInfo.txt

    The path AppleHardwareInfo.txt is relative to your current working directory, so this step moves AppleInfo/AppleHardware.txt to the current working directory (Documents) and renames it AppleHardwareInfo.txt.

  3. Use rmdir to remove the AppleInfo directory:

    ladmin@Mac-17 Documents % rmdir AppleInfo

    rmdir succeeds because AppleInfo is empty. rmdir removes only folders that are empty. Type rm -r to remove a folder that contains files. Here is an example:

    % rm -r AppleInfo

Create and Edit a Text File

macOS includes several command-line text editors. In this exercise, you use the nano editor to create and edit a file.

  1. Use nano to create a new file named fruit.txt:

    ladmin@Mac-17 Documents % nano fruit.txt

    Images
  2. Enter the following words in the file on separate lines. Press Return at the end of each line.

    apple

    pineapple

    grapefruit

    pear

    banana

    blueberry

    strawberry

  3. Press Control-X to quit nano.

    You see “Save modified buffer (ANSWERING “No” WILL DESTROY CHANGES)?”

  4. Type Y.

    You see “File Name to Write: fruit.txt.”

  5. Press Return.

    nano saves your file in the Documents folder inside your home folder, or ~/Documents, and exits, returning you to the prompt.

  6. Quit Terminal.

Edit and Re-secure Privacy Preferences

Earlier in this exercise, you allowed Terminal to access any files in the Documents folder. For security purposes, you should disallow this access to protect your Mac. Apple provides this setting as a default to protect you from malicious commands.

  1. Open System Preferences, then select Security & Privacy.

  2. Click Privacy.

  3. In the left sidebar, select Files and Folders.

    Earlier, you allowed Terminal access to your Documents folder.

    Images
  4. Deselect the Documents Folder checkbox.

    Images

    Terminal no longer has access to any files in your Documents folder.

  5. Quit System Preferences.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86