Terminal Tips

AppIconTerminalThe first thing to know about the Terminal is how to launch it, which you do by 
going to\Applications\Utilities\Terminal. Also, you’re no longer in graphical user-interface land: Most of what you’ll do in the Terminal is enter specific text strings, then press Return to execute them. When you see generic references like name-of-file or path-to-file throughout this article, replace that text with your file name or path.

Handy Terminal Pointers

  • Only text commands are accepted—you won’t use your mouse much inside of the Terminal, with a few exceptions like select games and other user interfaces.
  • After typing in a command, you can execute the command by pressing Return.
  • Every keystroke matters, including spaces, special symbols, and control keys.
  • Interrupt any running command by pressing Control-C.
  • Recall previously entered commands without retyping them by pressing the up arrow.
  • Curious about a new command? Type man command (where ‘command’ is the name of the command you’re having questions about), then press Return to read its instruction manual pages. For instance, man SSH will produce the manual for SSH. Press ‘q’ on the keyboard to exit the manual pages.
  • For a list of all commands available in the Terminal, hold down Escape, then press Y when prompted. Use the space bar to load more commands, and press ‘q’ to exit this view.
  • Page down through multipage results by pressing the space bar.
  • For commands that require the path to a file or folder, save yourself some typing by dragging and dropping the file or folder at the end of the command. The Terminal will automatically copy the dropped item’s path and name.
  • When typing out the path to a file, you can use the tab key to complete your typing. Simply type the first few characters of the name, then press tab. It’ll auto-complete the next letters for you.

Getting Around

When you first launch the Terminal application, your working directory (the directory you’re currently inside of) is your user’s Home Directory (the same directory that you can access in the Finder by clicking your name in the sidebar). You can test this by typing pwd (or ‘print working directory’) into the Terminal, then pressing enter. You’ll see the current directory printed out to the screen.

You can move to other directories by typing cd path/to/other/directory, replacing “path/to/other/directory” with the path name to the other folder that you wish to navigate to. When you press return, you’ll be taken to that directory (if it exists).

If you get lost, you can always return to your Home Directory by simply typing cd ~/ no matter where you’re at in the Terminal.

Anatomy of a Terminal Command

Unlike the sentences you were forced to diagram in sophomore English, Terminal commands only have three parts: the command, which calls a specific command-line utility; the options, which modify the command’s output; and the argument, which is typically the website, file, or other resource that the command will be operating on.

Remembering how the Terminal commands are created will help you in the future when experimenting with new commands and command line programs that take additional options and arguments.

Get Comfortable in Your Shell

The Terminal app is Apple’s implementation of a traditional UNIX command-line environment, called the shell. Since the introduction of OS X, Apple has used a particular shell instance called the Bash shell, and this is what you see by default when opening the Terminal application. You can verify this in Terminal | Preferences | Startup, and checking the option for “Default login shell”.

There are a myriad of different shells that you can use with the Terminal application; however, you will need to install most custom ones that don’t ship with OS X.

It is important to note that if this article inspires you to Google even more command-line tricks, remember that some command-line utilities are shell-specific, meaning that what works in Tcsh on that helpful blogger’s Linux box might not work in Bash on your Mac.

Clearing the Screen

After you begin typing a lot of commands into the Terminal, the scrolling history becomes longer and longer as all of the content for a single session (a session is created each time you open a new Terminal window or tab), it may become necessary to clear the screen to get a fresh view of what you’re trying to accomplish.

There are two ways in the Terminal application to clear the screen.

The first way is using the UNIX command called clear. When you type this into the Terminal, followed by the enter key, all of the content will be removed, and you’ll be presented with a new prompt, ready to type in more commands without the distractions.

Using the clear command, however, will keep all of the original content and you can still access this by scrolling up. To completely irradiate the content from previous commands in this scroll view, simply press Command + K. This Terminal-specific command will reset the Terminal window, giving you a pristine working area.

A different approach to this is to use Option + Command + K to clear only the scrollback. When you type this command, all of the scroll back content will be erased, while the currently visible command will still be viewable.

OS X’s Hidden Preferences

When it comes to customizing the look and feel of your Mac, the options listed in System Preferences only scratch the surface. Hiding throughout the OS are dozens of hidden preferences that can only be changed through the defaults command. Too many exist to list them all here, so we’ve compiled our five favorites. Always remember to quit an application before modifying its defaults. You can reset any of these commands by replacing TRUE with FALSE and executing the same command again.

Disable the Auto-Restore Feature of OS X

With OS X Lion, Apple introduced a feature that auto-restored files when opening up applications (such as opening up Preview and having all of your recently accessed PDFs appear), and this can sometimes happen even if you closed the application correctly. Both Preview and QuickTime are two main culprits here, and you can disable this auto-restore feature in both of these applications.

To do this, open the Terminal and type the following command:

defaults write com.apple.Preview NSQuitAlwaysKeepsWindows -bool false

That will disable the feature in Preview, but if you also want this feature disabled in QuickTime Player, then you can type this command as well:

defaults write com.apple.QuickTimePlayerX NSQuitAlwaysKeepsWindows -bool false

You’ll need to quit and restart the apps to see this change take effect, and if you want to reverse this, then run the same commands above, replacing “false” with “true.”

Show Hidden Files in The Finder

Believe it or not, the files you see listed on your Desktop in the Finder do not represent all of the files contained in your Desktop folder. In almost every folder, the OS hides system files that Apple considers too important for the likes of us to mess with (or too mundane for us to be bothered with). Now and again, though, it’s useful to view these files. To see the full contents of all folders in the Finder, execute the following command:

defaults write com.apple.finder AppleShowAllFiles TRUE

You should note here, however, that any files that begin with a dot are, by UNIX nature, hidden files. These files can be system files that are necessary to handle folder and file management. Be sure to keep this in mind before deleting or editing any files that don’t look familiar to you.

Change the File Format for Screenshots

Have you ever taken a screenshot on the Mac and gotten back a PNG file, but longed for a different file format instead? Fortunately, you can save them in a variety of formats, including PDF, JPG, and GIF just to name a few. Switching to your preferred format by executing the following command in the Terminal:

defaults write com.apple.screencapture type extension

Replace the “extension” word in the command above with the name of the file extension that you actually want as a screenshot. For instance, if we wanted JPG, you could type the following command:

defaults write com.apple.screencapture type JPG

When you press return, then log out of your Mac and back in, screenshots will taken using this new format instead of PNG. Pretty nifty, eh?

Disable the Dashboard

As with most Mac users, we’ve always had a love-hate relationship with the Dashboard. Released on OS X Tiger (10.4), we’ve always had a soft spot for this feature, but these days, it’s mostly just a waste of space on the Dock. Fortunately, you can remove this feature from OS X with ease. Simply open the Terminal and type in the following command:

defaults write com.apple.dashboard mcx-disabled -boolean YES

When you press return, you’ll need to enter one more command to make this new change take effect immediately. Type in the following command to restart the Dock and rid your Mac of the Dashboard feature:

killall Dock

If you don’t wish to enter the above command, then you can simply log out of your Mac and back in to see the change take effect.

Mac Security, Terminal Style

The Unix command line is where many (if not most) of OS X’s security practices were born — and it’s still the place to go to lock down files, resolve system conflicts, and erase your tracks. After all, UNIX gives the Mac it’s strong security foundation, and provides the basis for the Terminal command line.

Compress and Password-protect a File or Folder

Password-protected archives can’t be expanded by the Finder, a limitation that adds another layer of hassle, er, security.

The Finder can make ZIP archives from files and folders in one click from the File menu or the right-click contextual menu. When security is an issue, the Terminal’s zip command supersedes that with its ability to encrypt archived files and folders. The encryption standard is relatively weak by military or industrial standards, but it should be more than enough to defeat a nosy boss or family member.

To create an encrypted archive from a folder in the current directory, execute the following command:

zip -re archiveName name/of/folder

In the above command, replacing name/of/folder with the path and name of the folder you’d like to compress and archiveName with the name you’ve chosen for the zipped file. To retrieve the contents of an encrypted archive, execute unzip archiveName.

Fix File Permissions

In a multiuser system such as OS X, file permissions ensure privacy and security. Now and again, though, they can cause problems, especially when different users are swapping things through a shared folder on the same machine. If the permissions controls in the File Info dialog fail to resolve a problem, chmod and chown are certain to.

Generally, chmod is used to assign role-based permissions for users other than the owner. To ensure that anyone can open and modify a file, execute this command:

sudo chmod 777 path-to-file

Replace path-to-file with the actual file path and name of the file, which you can generate automatically by dragging a file from the Finder window into the Terminal window. When run, this command assigns full permissions to anyone who uses that machine, which is bad for security but good for convenience.

For more limited permissions, execute this command instead of the one above:

sudo chmod 644 path-to-file

Using this second command allows anyone to access and open the file, but only the file’s owner can modify it. To modify permissions on a folder and all of its contents, add the -R option after the command name.

Chown, on the other hand, assigns ownership of a file to particular user. If a file you’ve copied from someone else’s account refuses you access, execute the following command:

sudo chown your-short-user-name path-to-file

Securely Erase Free Space on Your Mac

It may sound strange, but deleted files aren’t actually deleted. Emptying the trash merely tells the operating system to mark the space as available, without actually removing the data that occupies that space on the drive. When new data needs the space, it writes over the old data, but until then, anyone with the right software can still recover the original data, and sometimes this recovery can still happen long after you’ve actually emptied the Trash on your Mac.

Disk Utility offers a one-line Terminal command to scrub free space of existing data. Execute this command:

diskutil secureErase freespace 3 /Volumes/name-of-drive

You can get the name of your drive by using the following two basic commands to look up the available system drives:

cd /Volumes/

ls

This will list the available drives, which you can copy and paste into the above command for the “name-of-drive” path.

diskutil is the command line equivalent of using the Disk Utility application on your Mac (located in /Applications/Utilities).

The utility will write to each drive sector 35 times, using a special algorithm. Thirty-five passes is well above the U.S. Department of Defense’s own standard for erasing data, which requires only seven passes for wiping data from a drive.

Note that with large capacity drives, this process may take a long time (perhaps days) to complete due to the capacity and work that needs to take place to do a 35-pass wipe of the data.

A Note About Sudo

Note that chmodchown, and several other commands in this tutorial are running under sudo, which requires an administrator’s password before executing the proceeding command.

Sudo is a super user account that is built into UNIX-based systems, and because it executes commands as the administrator, overriding the system’s usual warnings and precautions, you should be extremely careful when using this command.

Be extremely cautious with this. If sudo tells the system to erase the entire hard drive, for example, the system will happily do it, no questions asked. You should always double-check what you’ve typed when performing a sudo command. The commands using sudo in these tutorials are relatively safe, but you can get into trouble if you don’t know what you are doing here.

Remotely Control Another Mac

Terminal commands aren’t limited to just the local computer sitting in front of you. One of their most practical applications is controlling other Macs through remote shell connections (or SSH). Continue reading, and we’ll show you how to do this and possibly cause mischief with your co-workers and roommates with this functionality.

Establishing a Secure Shell Connection

SSH, or secure shell, opens a Terminal session on a remote machine, so all commands are then executed in the remote Terminal rather than the local one. The connection is encrypted, meaning none of the traffic passing between the two machines can be read if intercepted.

To get started, first make sure that SSH log-ins are enabled on the remote Mac by opening System Preferences and selecting the Sharing pane. Check the box next to Remote Login, and the SSH service will activate.

To connect to a remote computer via SSH, open the Terminal on the local machine and execute this command:

ssh -l username remote-address

Replace username with your username on the remote Mac and remote-address with the remote Mac’s IP address. (The remote IP address is listed in the remote machine’s Sharing pane when you click on Remote Login.) Press Return, and enter the remote username’s password at the prompt. SSH will connect you to the remote machine. (If you’re asked to add the remote machine to a list of known hosts, press Y for yes.) Once you’re connected, you can execute any Terminal command remotely.

This tutorial assumes you only want to connect to other machines on your local network, but you can also connect to Macs across the Internet using SSH.

Freak Out Your Roommates

There are hundreds of useful remote commands, but let’s get you started with a good gag. If you know that someone else is using the remote computer, SSH into the machine, and execute:

say “Ouch. Don’t press the keys so hard.”

The remote machine’s default voice will read the statement over the speakers. This is even funnier if can do it from a laptop in the next room. (Please use this power responsibly. Impersonating deities or the NSA is bad form.)

Pranks aside, say can quickly create a machine-read audio book from a text file. Execute say -osavedaudio.aiff -f file-to-read.txt. Say will convert the file and save it as savedaudio.aiff in the Terminal’s current directory.

Troubleshoot a Remote Server’s Network Connection

Remote servers are great — until they stop responding. Then one of the first questions to answer is whether the entire machine has gone offline or whether a particular service (such as remote log-in) has stopped responding.

To find out, execute the following command in the Terminal:

ping remote-address

Replace “remote-address” with the domain name, hostname, or IP address of the remote server. For instance, to ping our server from work, we execute:

ping maclife.com

The utility will send a generic knock-knock to the server. If the server is still operating and attached to the network, ping will display each response, along with the time it took to receive it.

Note that in order for this to work properly, the server on the receiving end must be able to respond to ICMP packets. With modern server architecture, and for security purposes, many server administrators have turned these features off on servers, so your mileage may vary.

Copy Files Across a Secure Network Connection

The next time you leave your thumb drive at home, grab the files you need over the network with secure copy, or SCP, which piggybacks on SSH, so you’ll need Remote Login enabled on the remote machine. The syntax for this command can get a bit long — in addition to the remote machine’s address and log-in info, you’ll need the names and locations of the files you want to copy — but it’s well worth the effort if it saves your bacon for that big client presentation. Like SSH, SCP transfers data over an encrypted connection.

To copy a file from a remote machine by executing the following command:

scp username@remote-address:path-to-file target-file

For instance, to copy a file called rental_agreement.doc from our remote machine to a new file called agreement.doc on our local machine, we’d execute:

scp tandorra@10.0.1.5:/Users/tandorra/Desktop/rental_agreement.doc agreement.doc

Obviously, the burden in this situation is knowing the exact location and name of the file before transferring it. Copying a file from your local machine to a remote one is a little easier. In that situation, we’d execute this command instead:

scp file-to-copy user@remote-address:path-to-new-saved-file

In our example, we could also replace our originally copied file–agreement.doc–to the remote machine with this command: scp agreement.doctandorra@10.0.1.5:/Users/tandorra/Desktop/agreement.doc.

Turn Off a Mac Remotely

If you need to turn off a Mac after leaving the house, SSH into the machine, and execute the following command:

sudo shutdown -h now

You’ll be required to enter your admin password because this command will kick all of the users off of the system and restart the machine at all cost. So, be sure that you don’t have any important work being performed on the Mac you’re about to switch off.

Manage and adjust text

If you like Spotlight and Search on your Mac, then you’ll love grep. This is an old-school pattern-matching utility that comes standard on many UNIX-based machines, including the Mac.

Like Spotlight, grep searches the full contents of files. Unlike Spotlight, however, grep specializes in locating patterns, which makes it ideal for analyzing text documents. Meanwhile, diff, fmt, and textutil offer other ways to quickly compare, format, and manage text files.

Find Patterns in Text Docs

One of our favorite uses of grep is checking finished documents for words and phrases we use too frequently. For instance, we tend to overuse compound sentences joined by “but.” The following command tells us how many lines in article.txt contain the offending word:

grep -ic but article.txt

In this example, the i option tells grep to ignore case (counting both uppercase and lowercase instances), and the c option tells it to return only the number of matches, not all of the lines in which the search term appears. For details, execute man grep.

Compare the Differences Between Two Text Files

Here’s one for writers, office workers, and coders who deal with a lot of document revisions and file revisions. The next time you need to quickly compare the differences between two text files, execute this command:

diff -y firstfile secondfile

Replace “firstfile” with the path and name of the first file (remember that you can drag and drop files into the Terminal to have their paths automatically inputted for you). Next, replace “secondfile” with the path and name of the file that you wish to compare with the first.

The -y option tells diff to split the output into two columns, one for each file, so the differences can be seen more easily.

Combine and Convert Documents of Any Type

Not everyone wants or needs a copy of Microsoft Word. Unfortunately, we all sometimes need to work with Word documents. Textutil can convert between Word, rich-text, and plain-text formats — and it can combine multiple documents, change fonts, and adjust font size while doing it.

To convert and combine all Word documents in the current directory to a single rich-text document called combined.rtf, execute this command:

textutil -cat rtf -output combined.rtf *.doc

Sometimes, of course, you only need to convert a single file. Use this command to do so while changing the font to 12pt Helvetica:

textutil -cat rtf -font Helvetica -fontsize 10 -output converted-file.rtf file-to-convert.doc

 

OS X Tweaks

One of the reasons we use Macs is how self-sufficient OS X tends to be. Most of the time, system maintenance occurs in the background, and mundane tasks that do require user participation (backups, for instance) are made as painless as possible (thank you, Time Machine.) For those times when we want or need more system-level control, these are the Terminal commands to rely on.

Backup in a Snap

Time Machine is a great way to make sure that all of your files and the entire operating system is always backed up in case anything should happen to your Mac. But, did you know that you can also back up on-demand with Time Machine using the tmutil commands available in the command line?

To back up your Mac, simply execute this command in the Terminal:

tmutil startbackup

After pressing enter, your Mac will go to work and begin creating a new backup. You can also stop the backup at any time by executing this command instead:

tmutil stopbackup

Identify and Eliminate Memory Hogs

When sluggish performance slows your desktop to a crawl, a runaway application might be the culprit. Check CPU and memory usage in all open applications by executing top. The command returns a list of every running process our your Mac, along with its allocated resources. The CPU field is easy enough to interpret–any process using more than half is sure to slow others down. The memory fields are a bit more complicated but, in general, the bigger the numbers, the greater the drain on your system.

If the problem app is visible on the Desktop, quit it as you normally would, using Command + Q or, if that fails to respond, using Force Quit (Command + Option + Escape).

But if the culprit is a lower-lever utility that runs behind the scenes, you’ll need more Terminal magic to end its misadventures. Make note of the problem process’s number in the PID column, and execute this command:

sudo kill PID-number

In the command above, replace PID-number with the application’s actual process number. The targeted process will terminate, freeing up its system resources.

Be extremely careful when killing background processes. Some are necessary for OS X to function properly. Only kill process when you know for a fact that they are bogging down your Mac, and that you started the process and it’s not a system process.

Find Free Space on All of Your Drives

If you have a Mac with multiple drives, with specific drives for iTunes, movies, music, and photos, then it may be hard to see exactly how much free space is available on your Mac at a single glance. Fortunately, the Terminal can help out quite a bit with this investigative process.

To see all of your free space available to you, execute this command inside of the Terminal application:

df -hl

When you do this, you’ll get a listing of the drives available to your Mac, and the percent capacity remaining on those drives. You might find that you have a lot more space than originally thought.

Generate Screenshots

If OS X’s default screenshot settings don’t meet your needs, you can assign image formats and file names for screenshots on the fly with screencapture, which lets you take shots of DVD Player (usually forbidden by the Finder at the insistence of the movie industry’s copyright lawyers). To create an instant, noiseless capture, execute this command:

screencapture -x -t jpg capture.jpg

Replace jpg with the 3-digit abbreviation for your chosen file format (PDF, TIF, GIF, and PNG are also available) and capture.jpg is the name of the saved file.

Using this command, you can also grab hard-to-get screenshots like screenshots of the login screen on OS X.