Command-Line Recipes - Take Control of the Mac Command Line with Terminal (2015)

Take Control of the Mac Command Line with Terminal (2015)

Command-Line Recipes

You’ve learned about the raw ingredients and the tools you need to put them together. Now it’s time for some tasty recipes that put your knowledge to good use! In this chapter, I present a selection of short, easy-to-use commands and customizations you can perform in the bash shell. Many use features, functions, and programs I haven’t yet mentioned, and although I describe essentially how they work, I don’t go into detail about every new item included in the recipes. Just add these herbs and spices as directed, and enjoy the results!

Misplaced hyphens! Your ebook reader may insert extra hyphens into longer lines of command-line text shown in this ebook. Please see the first item under Basics, earlier, for more information about how to avoid extra hyphens.

Change Defaults

Most Mac OS X applications, from the Finder to Mail to iTunes, store their settings in specially formatted property list, or .plist, files. Surprisingly, applications often have hidden preferences that don’t show up in their user interfaces—but if you put just the right thing in the preference file, you can change an application’s behavior in interesting ways, or even turn on entirely new features.

One way to edit preference files is to open them in a text editor, or in Apple’s Xcode development environment (which is available as a free download from the Mac App Store). But another, often easier way, is to use a command called defaults which can directly add, modify, or remove a preference from a .plist file. The recipes in this first set all use the defaults command.

Before using these commands to alter an application’s defaults, quit the application if possible (obviously that’s not an option with the Finder or the Dock, but the recipes that involve those apps include directions to force-quit and relaunch them).

Tip: Many Web sites list find hundreds of additional settings you can change—for example, at defaults-write.com, dotfiles, and Secrets.

Expand Save Dialogs by Default

Ordinarily when you use an application’s Save or Export command, the Save dialog that appears gives you only a simple pop-up menu from which to select a location for a file; you have to click the triangle button to expand it so it shows your entire computer. To make all Save dialogs appear in their expanded state by default, enter this:

defaults write -g NSNavPanelExpandedStateForSaveMode -bool TRUE

(To reverse this setting, repeat the command, changing TRUE to FALSE.)

Show Hidden Files in the Finder

By default, the Finder keeps some files and folders hidden—those whose names begin with a period and many of the Unix files and directories at the root level of your disk.

That’s usually good, because it prevents you from changing things that could cause your computer to break, but if you want to see all your files and folders, enter this:

defaults write com.apple.finder AppleShowAllFiles TRUE; killall Finder

(To reverse this setting, repeat the command, changing TRUE to FALSE.)

Prevent Dock Icons from Bouncing

When an application wants to get your attention, its Dock icon usually bounces. If you find this distracting and want to turn off the bouncing, enter the following:

defaults write com.apple.dock no-bouncing -bool TRUE; killall Dock

(To reverse this setting, repeat the command, changing TRUE to FALSE.)

Change the Screenshot Format

When you take a screenshot in Mac OS X (using either the Grab utility or the Command-Shift-3 or Command-Shift-4 keyboard shortcuts), the resulting pictures are normally saved, on your Desktop, in PNG (Portable Network Graphics) format. If you prefer another format, such as JPEG, enter this:

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

Use the same command, but substitute TIFF, PNG, or PICT for JPEG to use one of those formats.

Create Screenshots without Window Shadows

You can take a screenshot of a window by pressing Command-Shift-4, then pressing the Space bar and clicking the window. When you do so, the screenshot includes a large, translucent drop shadow, which might not be what you want. (You’ll notice that we leave out the shadows in most of the screenshots in Take Control books to save space while making the graphics larger and more legible.)

It’s easy enough to zap the shadows after the fact using Photoshop or various other graphics utilities, but if you want to avoid capturing them in the first place, use this command:

defaults write com.apple.screencapture disable-shadow -bool TRUE; killall SystemUIServer

To resume capturing shadows, repeat the command but with FALSE instead of TRUE.

Use Single-App Mode

If you have lots of apps open and find all that screen clutter visually distracting, you could manually hide each app (other than the one you’re currently using), or you can switch to an app while simultaneously hiding all the rest by Option-clicking the app’s Dock icon.

But if you’d prefer to have OS X hide all background apps automatically, you can do so with this command:

defaults write com.apple.dock single-app -bool TRUE; killall Dock

After you do this, switching to any app not only brings it to the front but also hides any other running apps (without quitting them). To return to the standard behavior, repeat the command but with FALSEinstead of TRUE.

Copy Text from Quick Look

Mac OS X’s Quick Look feature lets you select a file in the Finder and press the Space bar for an instant preview. It’s much quicker than opening an app just to view the file, and it works with most common file formats, including plain text, Microsoft Office files, documents from Apple apps like Pages, Numbers, and Keynote, as well as graphics, sounds, videos, and more.

There’s just one problem: if you want to select a portion of the text in one of these files and copy it, you’ll have to launch the app, because Quick Look doesn’t let you highlight and select text…unless you use this handy command:

defaults write com.apple.finder QLEnableTextSelection -bool TRUE; killall Finder

After using this command, try Quick Look on a text or word processing document, and while the preview is visible, you should be able to select and copy text. To reverse the command, replace TRUE with FALSE.

Disable App Nap

10.9 Mavericks introduced a performance-enhancing, energy-saving feature called App Nap. App Nap intelligently reduces the system resources used by background apps, in order to make the foreground app more responsive while using less power overall. However, sometimes you may not want your background apps to nap—you may want them to have access to your full system resources, for example to perform a complex calculation or graphics operation while you work on something else.

You can disable App Nap for any particular app by selecting it, choosing File > Get Info, and selecting Prevent App Nap. (If that checkbox is missing, that app doesn’t support App Nap anyway.) It’s usually preferable to disable App Nap one app at a time, because disabling it globally can dramatically shorten your battery life.

But if background performance is more important to you than power savings and you’d like to disable App Nap globally, you can do it like this:

defaults write NSGlobalDomain NSAppSleepDisabled -bool TRUE

As usual, reenable it by replacing TRUE with FALSE.

Press the Power Button to Show the Shutdown Dialog

Prior to 10.9 Mavericks, pressing the power button (or key) on your Mac for a second or so displayed a dialog with Restart, Sleep, Cancel, and Shut Down buttons. But starting in Mavericks, Apple changed the behavior so that pressing that button (or key) for a second or so puts your Mac to sleep, while pressing Control-Eject brings up the shutdown dialog.

To restore the old behavior of displaying the shutdown dialog by pressing the power button (or key), enter this:

defaults write com.apple.loginwindow PowerButtonSleepsSystem -bool FALSE

If you change your mind later, you can undo this command by repeating it with TRUE in place of FALSE.

Stop the Help Viewer from Floating

This may be my favorite “defaults” recipe of all time. In recent versions of OS X, the Help window (which appears when you choose most commands from any application’s Help menu) floats above all other windows, no matter what you do. You can minimize it to the Dock to get it out of the way, but that makes it awkward for switching back and forth between the Help window and your app.

With this simple command, you can make the Help window act like any other window—it’ll appear in front initially, but you can click another window to bring that window in front of the Help window. Here’s the command:

defaults write com.apple.helpviewer DevMode -bool TRUE

To return the Help window to its irritating always-float behavior, repeat this command with FALSE instead of TRUE.

Use a Separate Password for FileVault

Do you use FileVault to protect your Mac’s data? Good for you! (If not, you might want to check out my book Take Control of FileVault.) Ordinarily, you unlock FileVault in the process of logging in with your regular account password. But if you’re extremely security-conscious and want to use a different password for FileVault than your login password, you can—using a defaults write command, of course. Be aware that you’ll face two consecutive login prompts whenever you start or restart your Mac—the first to unlock FileVault, and the second to log in to your user account.

The way to accomplish this is to turn off FileVault’s Auto-login feature, which normally logs you in to your account using the same password you just entered to unlock FileVault. To do this, enter:

sudo defaults write /Library/Preferences/com.apple.loginwindow DisableFDEAutoLogin -bool TRUE

After you do this, you’ll get two password prompts when you restart, but the two passwords will still be the same. You can’t (readily) change your FileVault password, but you can change your account’s login password in System Preferences > Users & Groups > Password by clicking Change Password and following the prompts.

To return to automatic login, first change your login password back to match your FileVault password, and then use this command:

sudo defaults delete /Library/Preferences/com.apple.loginwindow DisableFDEAutoLogin

Perform Administrative Actions

This group of recipes involves administrative tools—things you might need to do on a multi-user Mac, a server, or a remote Mac.

Use Software Update from the Command Line

If you want to update Apple software on your Mac from the command line instead of using the Updates view of the Mac App Store app, or if you want to update Apple software on a remote Mac via SSH, enter the following command:

sudo softwareupdate -i -a

The -i and -a flags together mean “go ahead and install every available update.” Note that even though Apple rolled the features of Software Update into the Mac App Store starting with Mountain Lion, this command applies only to Apple software, not to third-party software downloaded from the App Store.

List Your Mac’s Reboot History

When did you last boot your Mac? A quick way to check is to enter:

last reboot

The answer will appear in this format (possibly with earlier reboots listed first, depending on your Mac model and the version of Mac OS X you’re using):

wtmp begins Sat Mar 21 10:33

Show How Long Your Mac Has Been Running

A slightly different take on the previous recipe is a command that tells you the elapsed time since your last (re)boot (as opposed to the raw date and time):

uptime

The answer will look something like this:

19:09 up 4 days, 22:32, 3 users, load averages: 1.47 1.82 1.87

In this display, the first group of numbers is the current time. That’s followed by how long the Mac has been running since its last (re)boot. In this example, it’s been up for 4 days, 22 hours, and 32 minutes. The remainder of the line shows the number of users and load averages over the last 1, 5, and 15 minutes—all of which you can usually ignore.

List Users Who Logged In Recently

Is your Mac used by a number of different people? Do users sometimes log in remotely? If you’d like to know who’s been logging in recently, you can get a lengthy list with this command:

last

This command lists the users who have logged into this machine, the IP address or terminal from which they logged in, and important system events such as shutdowns and restarts.

Restart Automatically after a Freeze

If your Mac locks up completely while you’re present, you can hold down the power button for several seconds until it turns off completely, and then press the button again to turn it back on. But if an unattended Mac freezes, it will sit there, frozen, until someone comes along to restart it. That could cause problems, especially when that Mac is functioning as a server, or if you need to access its files remotely.

To tell your Mac you want it to attempt an automatic restart in the case of a system freeze, enter this:

sudo systemsetup -setrestartfreeze on

This feature doesn’t work all the time, but it’s worth a try. Repeat the command with off instead of on to return to the default behavior of staying frozen until you do something about it manually.

Find Interesting Stuff in Log Files

Many Unix and Mac OS X applications and background processes constantly spit out log files detailing what they’ve been up to and, perhaps most important, any errors they’ve encountered. Most system processes store their log files in /var/log, and although you can open them in any text editor, they tend to be so long and inscrutable as to make the exercise more bother than it’s worth. Luckily, you can use the grep command to sift through log files looking for specific strings.

For example, to look through the main system log for every instance of the word error (a sure sign of an interesting entry), enter this:

grep error /var/log/system.log

Or, to look for all entries involving Time Machine (whose background process is called backupd), enter this:

grep backupd /var/log/system.log

If you’d rather have a paged display instead of dumping the output directly onto the command line, you can pipe it through less, like so:

grep backupd /var/log/system.log | less

Modify Files

A number of common recipes involve modifying files in some way. Here’s a selection.

Change the Extension on All Files in a Folder

Yosemite’s Finder, at long last, has a built-in batch renaming function. Yay! But if you’re using an older version of Mac OS X, or if you simply want a handy way to rename a large number of files in one go from the command line, this recipe is for you.

The mv command, discussed in Move or Rename a File or Directory, has an unfortunate shortcoming in that it can’t rename a batch of files all at once with wildcards. But never fear, you can still get the job done.

Begin by creating the following shell script, using the instructions in Create Your Own Shell Script:

#!/bin/bash

for f in $3/*.$1; do

base=`basename $f .$1`

mv $f $3/$base.$2

done

Note: This script makes use of the backtick (`) character, which is called a grave accent when placed over a vowel. It’s on the same key as the tilde (~), and should not be confused with the apostrophe (') or the backslash (\).

Make sure it’s located somewhere in your PATH, and that it’s executable (see Understand Permission Basics, earlier). I call this script br.sh, for “batch rename.”

To run this script, enter the script name followed by the old extension, the new extension, and the directory in which to make the change—in that order.

For example, to change all the files in ~/Documents with the extension .JPG to end in .jpeg, enter this:

br.sh JPG jpeg ~/Documents

Decompress Files

If you decide to download Unix software (or source code to compile yourself), it may be packaged in any of several unfamiliar archive formats. As I mentioned in Decompress, a file ending in .tar is a “tape archive” (a way of bundling files together without necessarily compressing them); the extensions .gz and .bz2 refer to different compression mechanisms, and you may see a combination of these (such as archive.tar.gz).

To decompress and/or unpack these, use one of the following commands, based on the extension(s) the file has:

tar -xf archive.tar

tar -xzf archive.tar.gz

tar -xjf archive.tar.bz2

As you can see, each compression format requires a different flag—use -z for .gz (or .tgz) and -j for .bz2 (or .bz).

Although they’re more common in the Windows world than in the Unix world, you may also encounter files compressed with Zip (.zip). You can decompress these in the Finder by double-clicking them, but if you want to do so on the command line, you can do it like this:

unzip archive.zip

Convert Documents to Other Formats

Mac OS X includes a marvelous command-line tool called textutil, which can convert text documents between any of numerous common formats. This can be particularly useful in cases where you don’t have Microsoft Word, or aren’t satisfied with the way it saves files in other formats. Here are a couple of examples.

Convert a File from RTF to Word (.doc)

To convert the file file1.rtf (RTF format) to Word format (.doc) and save it as file2.doc, enter this:

textutil -convert doc file1.rtf -output file2.doc

Convert a File from Word (.doc) to HTML

To convert the file file1.doc (Word format) into HTML format and save it as file1.html, enter the following:

textutil -convert html file1.doc

(When no filename is specified, textutil uses the same filename with an extension corresponding to the format you requested.)

Note: The textutil program supports other formats too; just substitute the format of your choice for doc or html in the examples above. Among the most useful options are txt (plain text), html (HTML), rtfd (RTF with attachments), docx(Open Office XML), and webarchive (Web archives, like Safari uses).

Work with Information on the Web

The command-line environment includes a handy program called curl that can connect to Web, FTP, and other servers and upload or download information. Here are a few examples of how to use it.

Download a File

If you know the exact URL of a remote file on a Web, FTP, SFTP, or FTPS server, you can fetch it with this simple command (fill in the URL as appropriate):

curl -O URL

(Again, that’s an uppercase letter o, not a zero.) The file is downloaded to your current directory.

Save a Local Copy of a Web Page

When you browse the Web in Safari, you can save the source of any Web page. You can do the same right on the command line, without ever opening a browser, using this command:

curl URL > filename .html

For example, to save the source of the TidBITS home page to a file named tidbits.html, you can enter this:

curl http://tidbits.com/ > tidbits.html

Note that this command doesn’t download graphics, style sheets, or other files linked from the Web page, so the page may not look entirely correct if you open it in a browser.

Put the Source of a Web Page on the Clipboard

What if you don’t want to save a Web page to a file, but instead want to put it on your Clipboard so you can paste it into another application? Enter the following:

curl URL | pbcopy

For example:

curl http://tidbits.com/ | pbcopy

Manage Network Activities

The following several recipes involve ways of getting information about local and remote networks, and the computers running on them.

Get Your Mac’s Public IP Address

If your Mac is connected to the Internet using a gateway, modem, or router, its private IP address (the one you can see in System Preferences > Network) probably isn’t the same as the public address that other computers see.

To find out your Mac’s current public IP address, enter this:

curl -s http://icanhazip.com/simple/; echo

The echo command is there only to make sure there’s a blank line after your IP address when it’s reported, to improve readability.

Get a List of Nearby Wi-Fi Networks

The Wi-Fi menu in your menu bar lists nearby Wi-Fi networks. But if you’ve turned off that menu, or simply want to get at that information from the command line, enter this:

/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -s

It displays nearby networks’ names (SSIDs), MAC addresses, encryption types, and other useful information. To learn what else this tool can do, substitute the -h (help) flag for -s. Yes, the full path is needed for executing this command: if you think you’ll use it often, you can set up an alias for it (see Customize Your Profile, earlier).

View Your Mac’s Network Connections

Which servers and other network devices is your Mac currently connected to? For all the details (in fact, far more details than you probably want), try:

netstat

The netstat command spits out a tremendous amount of detail about which protocols are sending data to or receiving data from which addresses on which ports and a great deal more. It can be overwhelming but also fascinating to get a glimpse into what processes are doing various things online. (And don’t forget, there’s always man netstat—see Get Help.)

Find Out Which Applications Have Open TCP/IP Network Connections

You take it for granted that your Web browser and email program are connected to the Internet. But what other apps or background processes have network connections? Is anything covertly “phoning home?”

To see a list of processes you own that are accessing the Internet right now, enter this:

lsof -i

To see a list of all processes accessing the Internet, enter:

sudo lsof -i

Either way, you get a list of the processes on your Mac that currently have Internet connections, along with the domain names or IP addresses to which they’re connected, the ports they’re using, and other useful tidbits.

Determine If Another Computer Is Running

Did your server crash? Is another Mac on your network turned on and awake? The easy way to find out if another computer is on, awake, and connected to the network is to use the ping command.

Enter this (substituting the remote computer’s domain name or IP address):

ping address

If you see a sequence of lines that look something like this, the computer is responding:

64 bytes from 216.168.61.41: icmp_seq=0 ttl=49 time=79.27 ms

Press Control-C to stop pinging. If more than 30 seconds go by without any such line appearing, either the computer is offline, it is configured not to respond to pings, or there’s a network problem.

Get Information about an Internet Server

What’s the IP address of that Web server you’re connecting to? An easy way to find out is to use the host command:

host domain-name

This command returns the IP address(es) for that domain name. It also indicates if the domain name is an alias to another computer, and it lists any mail exchange servers associated with that domain. For example, enter host www.takecontrolbooks.com to learn the IP address of the Take Control Web server, the fact that www.takecontrolbooks.com is actually an alias (pointer) to a computer called takecontrolbooks.com, and the domain name and IP address of the takecontrolbooks.com mail exchange server.

Alternatively, you can use a command called nslookup (name server lookup) command, which takes either a domain name or an IP address as an argument:

nslookup tidbits.com

nslookup 173.255.250.214

In addition to showing you a host’s domain name or IP address, nslookup gives you the IP address of the DNS server it consults, which can be handy to know if you’re trying to diagnose a DNS problem.

Note: A newer command, called dig (domain information groper—yes, really), works much the same way and can also supply the IP address of a domain name, but requires special flags to do reverse lookups of domain names from IP addresses and presents it output in a much less readable form than nslookup or host.

Get Information about a Domain Name

If you need to find out what person or organization owns a domain name, enter the following:

whois domain-name

For example, if you enter whois tidbits.com, you’ll likely learn which registrar handles the domain, the addresses of its name servers, and (perhaps) contact information for the domain’s owner. (Many domain registrations omit owner contact information to preserve privacy.)

Flush Your DNS Cache

When you connect to any Internet service (a Web server, an email server, the iTunes store, or whatnot), your Mac asks a DNS server to convert the server name (like tidbits.com) into an IP address (like 173.255.250.214). Your Mac then stores that IP address for a while in a DNS cache, so that the next time you connect to the same server, it can skip the DNS lookup step and get you there a bit faster.

However, sometimes server addresses change, and sometimes your DNS cache can get corrupted. In either case, you might find yourself connecting to the wrong site (or not connecting at all). The simplest solution is to flush the DNS cache, forcing Mac OS X to look up IP addresses from scratch the next time you try to connect to each server by name.

The way you do this varies depending on your version of Mac OS X:

· 10.10 Yosemite: sudo discoveryutil mdnsflushcache

· 10.7 Lion–10.9 Mavericks: sudo killall -HUP mDNSResponder

· 10.6 Snow Leopard: sudo dscacheutil -flushcache

Note that since these commands use sudo, you’ll have to supply an administrator password.

Verify an RSA Fingerprint for SSH

In Step 2 of Start an SSH Session, I said you must confirm that the fingerprint you’re seeing for a remote computer matches the one it’s supposed to have. But how can you know what the computer’s fingerprint is supposed to be?

You can ask the administrator of the remote computer, if there is one. But if the computer is one of your own (or you at least have physical access to it), you can determine its fingerprint with the following command, which you enter in Terminal on that Mac:

ssh-keygen -l -f /private/etc/ssh_host_rsa_key.pub

The command above works for Macs running Yosemite. If the computer is running a different operating system or a different version of Mac OS X, the key might be located in another place (besides /private/etc), so you’ll have to find it—either using a command such as find or locate, or by searching the Web to find the key location for that particular operating system.

Work with Remote Macs

These two recipes help you work with Macs you’re accessing remotely.

Restart a Remote Mac

If you need to reboot the Mac you’re sitting in front of, you can simply choose Apple  > Restart.

But what if you’re logged in to another Mac via SSH? To restart it, just enter this:

reboot

Needless to say, you should use this with caution—anyone else who happens to be using the computer at the time might be unhappy!

Note: You can use this command to reboot your own Mac, too, but it’s usually safer to choose Apple  > Restart.

Restart a FileVault-protected Mac without a Password Prompt

If you need to remotely reboot a Mac that’s protected with FileVault, it’s possible to do so without the Mac getting stuck on the password screen when it turns back on.

First, make sure the remote Mac supports the authrestart command. You can check either by consulting Apple’s support article OS X: Macs that support authenticated restart with FileVault or by connecting to the remote Mac via SSH (or, if you have physical access to the Mac, launching Terminal on it) and entering:

fdesetup supportsauthrestart

If that command returns true, you’re good to go.

The command to restart the system immediately without a password prompt afterward is:

sudo fdesetup authrestart

Enter that, supply your administrator password, and the remote Mac should reboot without any further fuss.

Troubleshoot and Repair Problems

These next few recipes can help you solve problems that keep your Mac from working correctly.

Delete Stubborn Items from the Trash

Occasionally, you may find that no matter what you do, you can’t empty your Trash. Maybe you get an inscrutable error message, or maybe it just doesn’t work. If this happens, the first thing to try is choosing Finder > Secure Empty Trash. If that doesn’t work, however, try the following (taking all the necessary precautions associated with sudo, of course):

sudo rm -ri ~/.Trash/*

The rm command prompts you for confirmation to remove each item.

Warning! Do be certain to type these commands exactly right; using sudo rm can do some serious damage if you’re not careful!

If that doesn’t work, try each of these until the Trash is empty:

sudo rm -ri /.Trashes/*

sudo rm -ri /Volumes/*/.Trashes/*

Figure Out Why You Can’t Unmount a Volume

Have you ever tried to eject a CD, disk image, or network volume, only to see an error message saying the volume is in use? If so, the maddening part can be figuring out which process is using it so you can quit that process. So enter the following, substituting for VolumeName the name of the volume you can’t unmount:

lsof | grep /Volumes/VolumeName

This command shows you any processes you own that are currently using this volume; armed with this information, you can quit the program (using the kill command if necessary, as described in Stop a Program). One frequent offender: the bash shell itself! If that’s the case, you’ll see something like this:

bash 14384 jk cwd DIR 45,8 330 2 /Volumes/Data

If you’ve navigated to a directory on this volume in your shell, Mac OS X considers it “in use.” The solution in this case is to exit the shell, or simply cd to another directory.

If this command doesn’t tell you what you need to know, repeat it, preceded by sudo.

Find Out What’s Keeping Your Mac Awake

If your Mac refuses to sleep, it’s likely because some process is completing a task that prevents sleep from occurring immediately. But which process would that be? To find out, try this command:

pmset -g assertions | grep -E "(PreventUserIdleSystemSleep|PreventUserIdleDisplaySleep)"

The output will look something like this:

PreventUserIdleDisplaySleep 0

PreventUserIdleSystemSleep 1

pid 674(BitTorrent Sync): [0x0000003e000101db] 57:00:45 PreventUserIdl\

eSystemSleep named: "syncing"

The first line (PreventUserIdleDisplaySleep) tells you if anything is preventing display sleep (0 for no, 1 for yes), and the second line (PreventUserIdleSystemSleep) tells you if anything is preventing system sleep.

If the answer to either of these is 1 (yes), the line below lists the PID and name of that process—in this example, BitTorrent Sync, although you may also see Time Machine or any of numerous other processes.

Reset the Launch Services Database

Mac OS X’s Launch Services database keeps track of which programs are used to open which files, among other things. If you find that the wrong application opens when you double-click files, or that icons don’t match up with the correct items, you may need to reset your Launch Services database. Do it like this (enter the command as a single, long line—no space between LaunchServices. and framework and omit hyphens that you may see in the path):

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user

Because this resets a lot of default mappings, your Mac may think you’re launching applications for the first time and ask if it’s OK. Agree to the alerts and you should be in good shape.

Fix Disk Problems in Single-User Mode

If your startup disk has problems, the usual remedy is to use Recovery mode (which starts from a hidden Recovery HD volume), and then run Disk Utility. If your Mac doesn’t have a Recovery HD volume (installed automatically as part of Lion or later) and you don’t have another startup volume handy, try this recipe.

First, power on (or restart) your Mac while holding down Command-S to enter single-user mode. You’ll see a text display much like the inside of a Terminal window. Enter the following two commands, pressing Return in between:

/sbin/fsck -yf

The fsck utility (“file system check,” which is like a command-line version of Disk Utility) checks most of your disk for errors, and repairs those it can. To restart your Mac normally afterward, enter exit.

Get Help in Style

These two recipes let you read man pages in a friendlier environment than Terminal, without installing any extra software.

Read man Pages in Preview

The man command can save manual pages as beautifully formatted PostScript files, which Preview can then read. Because it’s a multi-step process, you need a shell function (like a shell script, but contained directly in your .bash_profile file) to help you do this. So, following the instructions in Customize Your Profile, put the following lines in your .bash_profile:

psman()

{

man -t "${1}" | open -f -a /Applications/Preview.app/

}

Having done that, to view a man page in Preview, enter the following, substituting the name of whatever command you want to read about:

psman command

Et voilà! After a few seconds, a spiffy manual page opens in Preview.

Read man Pages in BBEdit or TextWrangler

Perhaps you’re a plain text, monospaced font kind of person. If you keep BBEdit (or its free “little brother” TextWrangler) open anyway, you can use it to open man pages instead of the built-in man program.

To make this happen, install the command-line tools available for either editor, add the following line to your .bash_profile (see Customize Your Profile), and then start a new shell session:

export MANPAGER="col -b | bbedit --clean --view-top"

If you’re using TextWrangler, just substitute edit for bbedit in the command. Thereafter, entering man (followed by the command of your choice, such as man ls) displays the manual page in your text editor.

Do Other Random Tricks

Finally, we have a bunch of interesting recipes that didn’t fit neatly in any of the other categories. Enjoy!

Search Your Command History

Let’s say you entered some long, obscure command a while ago (or even in a previous Terminal session) and you don’t want to keep pressing Up arrow hundreds of times to find it. No problem—you can search your command history!

For starters, you could simply enter history to see a list of recent commands (the default is 512). But if you remember a portion of the command, you can filter that list with the following:

history | grep string

Replace string with whatever you remember from the command, such as history | grep chmod or history | grep nano.

Take a Screenshot

You can take a screenshot by pressing Command-Shift-3; the image is named Picture X by default and stored on your Desktop. But what if you want to take a screenshot and give it a different name, or store it somewhere else? Or—this is pretty cool—take a screenshot of a remote Mac you’re logged in to via SSH?

You can do it with this command (substituting the name and location of the saved screenshot to taste):

screencapture ~/myscreen.png

Compact a Disk Image

Of the numerous disk image formats Disk Utility can create, two of them—sparse disk images and sparse bundle disk images—have the interesting characteristic that they can expand as needed (up to a preset limit) to accommodate more files. (See my TidBITS article Discovering Sparse Bundle Disk Images.) The only problem is, they don’t automatically shrink again when you delete files!

To compact a sparse or sparse bundle image so that it takes up only the space it needs, enter the following, substituting the image’s name and location as appropriate:

hdiutil compact image.dmg

Use Text-to-Speech from the Command Line

This is mostly just for fun. To have your Mac speak text using the text-to-speech voice currently selected in System Preferences > Dictation & Speech (Speech in older versions of Mac OS X) > Text to Speech, enter the following:

say "Hello there"

Note that this even works remotely, assuming you’re logged in to a Mac on the other end. Use your power responsibly!

As a more practical example, you can make a quick-and-dirty countdown timer using a command like this, substituting for 60 the number of seconds to wait before the Mac speaks the text you enter:

sleep 60; say "One minute has elapsed"

Disable Your Mac’s Startup Chime

If you’re going to be turning on (or restarting) your Mac in a quiet environment where the startup chime would be distracting, you can turn it off with the following command:

sudo nvram SystemAudioVolume=%80

To reenable it, you use a somewhat different command:

sudo nvram -d SystemAudioVolume

Send an SMS from the Command Line

You can send an SMS text message from a phone, and with the combination of Yosemite and an iPhone running iOS 8, you can send an SMS using Messages on your Mac. But even without an iPhone—and with any version of Mac OS X—you can send an SMS from the command line! This might be useful in a shell script—for example, if you wanted a notification that a script completed successfully (or failed).

This command uses a free service from Ian Webster called TextBelt (consult the TextBelt site for more information):

curl -X POST http://textbelt.com/text -d number= mobile_number -d message=" message_text "

Fill in mobile_number with the 10-digit phone number (consult the TextBelt site for details on using the service outside the United States) and replace message_text with your message text.

Prevent a Laptop from Waking up When Jostled during Travel

Mac laptops are designed to go to sleep automatically when you close the lid and wake up automatically when you open the lid. But if your computer happens to be bumped just the right way while it’s in its case, the lid can open just enough to wake up the computer, potentially causing it to overheat, or causing your battery to run down, while it should be asleep.

To prevent the computer from waking up automatically when the lid opens, enter this:

sudo pmset -a lidwake 0

Thereafter, wake your Mac by pressing a key after you open the lid.

(To reverse this setting, repeat the command, replacing the 0 with a 1.)

List More Directory Information

You should be thoroughly familiar with the ls (“list”) command, introduced in See What’s Here. Among the flags that modify its behavior, I’ve described elsewhere in this book -l (long format) and -h (human-readable).

But if you want ls to truly show you everything, you need to add a few more flags.

To make the command easier to use, add an alias to your .bash_profile (see Create Aliases) like this:

alias lsl="ls -lah@e"

The flag -a lists all files, including hidden ones (those that begin with a period). The -@ flag lists extended attributes (indicated by an @ at the end of a permissions string), and the -e flag lists all access control lists, or ACLs (indicated by a + at the end of a permissions string). (And yes, I agree that the meanings of -@ and -e seem backward at first glance!)

Tip: For frequent very brief command-line recipes, follow Mark Krenz’s Command Line Magic Twitter account.