Jump to content

Five must-known commands for Mac OS X Terminal

+ 2
  d1taylor's Photo
Posted Apr 25 2012 05:50 AM

If you're an old-time Unix or Linux user like me, you know that one of the best parts of Mac OS X is that it includes a full command line world based on NetBSD under the hood. In fact, I always have the Terminal app open and it's a rare day that I'm not writing scripts or otherwise experimenting on the command line, even as my screen is covered with pretty graphical user interfaces and drag-and-drop features.

You can get any of a zillion books on Unix and Linux to learn more about "vi", "emacs", "ls", "grep", "find", etc, including my O'Reilly title "Learning Unix for Mac OS X ," but I want to talk more about what Apple has added to the standard list of commands available, because some of them are darn cool.

The problem is there's no central list of these command line additions and some are still included even though they've been obsoleted years ago. You can try something fancy while parsing the man pages like this:

$ grep .TH * | grep -E "(Apple Computer|Mac OS X)" | cut -d: -f1 | fmt
DeRez.1 Rez.1 RezDet.1 ant.1 certtool.1 cmpdylib.1 crlrefresh.1
gprof.1 ld_classic.1 lipo.1 mig.1 migcom.1 pbcopy.1 redo_prebinding.1
segedit.1 size.1 srm.1 strings.1 strip.1 tops.1


But the fact is it misses some of the most helpful additions from the team at 1 Infinity Way. All the more reason to read this article, right! So let's jump in …


Open

It's not the most exciting, but it's darn useful to be able to use the command line to quickly zip through lots of subdirectories and find files of various types buried in your system. Ready to see what's inside using the program that created the file? Simply specify "open _filename_" and your Mac will automatically show that file in the appropriate app.

For example:

$ open *png


will open up all the PNG graphic files in the current directory using whatever app you have specified as the default. Or, even more useful, "open http://www.nrp.org/" will feed that URL to your favorite Web browser.

Don't like the default app? "Open" has a ton of options to make it even more useful, including the ability to specify what app should be used to open the file, but here are the few that I think are most helpful:

    -a — Opens with the specified application.

    -e — Opens with TextEdit.

    -t — Opens with default text editor.

    -f — Reads input from standard input and opens with TextEdit.

    -R, -reveal — Selects in the Finder instead of opening.

    -g, -background — Does not bring the application to the foreground.


To put these together, I have written shell scripts that extract a URL from a text file, then opens it in Google Chrome (my default browser) in the background, rather than force my attention away from the Terminal window. Like this:

$ open -a chrome -g $URL


Very helpful when you need to jump back and forth between the GUI apps and Terminal.


2. PMSET

It may not seem very glamorous, but there's a lot you can do to fine-tune your Mac's behavior by spending some time digging into the "pmset" power management utility. I don't use it that frequently, but particularly with always-on servers, it's great to be able to fine-tune how it works.

You'll immediately see all of its cool options after using the '-g' flag to get your own power settings:

$ pmset -g
Active Profiles:
Battery Power		-1*
AC Power		-1
Currently in use:
 halfdim              1
 sms                  1
 panicrestart         15
 gpuswitch            2
 hibernatefile        /var/vm/sleepimage
 disksleep            10
 sleep                90 (sleep prevented by )
 hibernatemode        3
 ttyskeepawake        1
 displaysleep         5
 acwake               0
 lidwake              1


Here's where you can change settings that are otherwise crazy hard to find in the System Preferences windows, like whether you want your MacBook to wake up when you open the lid. Or, perhaps you'd like to have the computer wake up when it's plugged into the wall, even if it's closed? That's helpful if you like to leave a laptop docked, of course.

To change settings, specify the appropriate verb and add the parameter you want. For example, to switch to the display powering down after five idle minutes:

$ pmset -b displaysleep 5


The pmset command can also work with an attached uninterruptible power supply (UPS) if compatible. In that instance, you can specify details like how long after a power fail the system should fully shut down:

$ pmset -u haltlevel 20 haltremain 15


The above specifies that the system should perform an emergency shutdown if either the battery drains to less than 20% or the UPS reports less than 15min of battery remains. A bit more fancy than I use on a daily basis, but for a server, very helpful.

One more really neat example of pmset to whet your appetite for this powerful command: The follow command specifies that the Mac should wake up every morning at 7am:

$ pmset repeat wakeorpoweron MTWRF 7:00:00


Sure you can spend hours figuring out the fancy graphical way to set up the power management on your Mac server or laptop for your specific needs, but isn't this easier?


3. Size

You've probably read about how Mac applications include both Intel and universal binaries, but did you ever wonder how much space they take up? Once you know a bit about how Mac OS X actually uses a subfolder organization for applications on your Mac, you'll find you can use the "size" command to get more information about these than a regular Linux command.

"Pages," a part of the Apple iWorks suite, has its actual executable code located in a folder called "Contents", within a subfolder called "MacOS". Knowing that, here's how the program itself breaks down:

$ size /Applications/iWorks/Pages.app/Contents/MacOS/Pages 
__TEXT	__DATA	__OBJC	others	dec	hex
3432448	102400	262144	159744	3956736	3c6000	/Applications/iWorks/Pages.app/Contents/MacOS/Pages (for architecture ppc7400)
3428352	98304	290816	163840	3981312	3cc000	/Applications/iWorks/Pages.app/Contents/MacOS/Pages (for architecture i386)


At this point in 2012 I have to wonder why I still have PowerPC binaries, but fortunately disk space has become cheap, so while it's taking up space on my 500GB drive, it's not much. In fact, it's summarized in the "dec" column, meaning that the PPC and Intel versions each take up 3.95 MB. That breaks down into text, data, object code, and "other" as displayed.


4. Textutil

Leaving administrative tasks behind, it's an unfortunate reality of working on the command line that line endings and other character encoding sequences can get messed up as you travel from one operating system to another. If you've ever seen ^M on the end of each line of a text file, you know what I mean.

Fortunately, Apple's included a surprisingly helpful utility that can clean up a lot of these messes: textutil. Easiest way to learn about it is to simply invoke it with no arguments, which produces a raft of options. 

Let's start by using it to peek into files, however. Here's what it can tell us about a Word .doc file:

$ textutil -info Column-94.doc
File:  Column-94.doc
  Type:  Word format
  Size:  23040 bytes
  Length:  3197 characters
  Created:  2012-04-13 14:11:00 +0000
  Last Modified:  2012-04-13 14:11:00 +0000
  Contents:  PUBLICATION: THE DAILY CAMERA...


Way more interesting is that it can also actually convert files from one format to another. For example, let's extract all the text from the above Microsoft Word document and save it as a text file, suitable for further command-line manipulation. Easy:

$ textutil -convert txt Column-94.doc


The new '.txt' file is saved as Column-94.txt. Using this, we can quickly use command line tools like "grep" to search through Word archives without hitting all the weird unprintable characters and gobbledygook of the Word file formats:

for file in *doc
do 
   textutil -convert txt $file
done
grep _string we seek_ *txt


Fast and easy. The full set of formats suggests even more uses for this command: txt, html, rtf, rtfd, doc, docx, wordml, odt, or webarchive.

One more example: convert the output of "ls" into an HTML page:

$ ls -C | textutil -convert html -stdin


In this case the result is saved as "out.html". I'll let you figure out additional uses for this handy little utility.


5. pbcopy | pbpaste

I'll end with two commands that I use quite a bit in my scripts: pbcopy and pbpaste. They let you interact with the Mac clipboard, the place where things are saved when you use the File -> Copy and File -> Paste commands within GUI apps like Pages and TextEdit.

Why is that useful? Because if you're going to select and copy the output of a command line interaction, then paste it into an email message or document anyway, why not save the selection dragging and keystrokes?

Here's how I use it:

$ ls -C | pbcopy


Now the result of the "ls" command is in the Clipboard, so I can switch to Gmail and with a Cmd-V paste it directly into the message I'm composing. 

If you want to go in the other direction, you could figure out how many words are in the current Clipboard selection by using something like this:

$ pbpaste | wc -w
    223


That's a lot. Wonder what it is. Hmm ...

[code]$ pbpaste | head -1[code]

pbcopy takes the standard input and places it in the specified pasteboard. If no pasteboard is specified, the general pasteboard will be

Ah, that's right, it's a section from the pbcopy main page itself.


Summary

Most people who use Mac OS X live in the graphical interface and never even know about the Terminal app. Those that do delve into the underbelly of the operating system invariably stick with standard Linux command line utilities. But there's more to the Mac OS X command line and with a little bit of creativity and ingenuity, there are some pretty slick things you can accomplish by merging them together. I hope this has whetted your appetite!



Dave Taylor is a long-time Unix user and Mac fanboy, author of the "Learning Unix for Mac OS X" and tech blogger at AskDaveTaylor.com. You can find him on any of the popular social media sites too, start here: DaveTaylorOnline.com.

Tags:
2 Subscribe


4 Replies

0
  bhosmer's Photo
Posted Apr 25 2012 07:38 AM

Dave,

A good addition for the open section is using the . to open the current directory in finder. I use this all the time for massive file selections, or to get in to hidden directories using the command-line and then being able to browse them from the GUI.
 : Apr 25 2012 09:28 AM
I have always wondered what the Terminal command is for the equivalent (in DOS) for dir *.* /s

Which is: list all files (*.*) across all directories recursively.

Then you can get into dir *.docx /s (list all word docs in all my directories)
Alejandro Ramirez
Digital Photography Club
Administrator
0
  thor222's Photo
Posted Apr 28 2012 11:23 AM

@Alejandro:

To list files recursively, use
ls -R


To list all docx files in a directory hierarchy, you'd use the Unix 'find' command:

find . -name "*.pdf"


Roughly, that translates to: "Find, within the current directory and all subdirectories, files whose name matches the wildcard *.pdf". Find is a very powerful tool. Do a
man find
for more information!
0
  allogarage's Photo
Posted Apr 30 2012 07:43 AM

I didn't know Open command and clipboard ones, and I think it can be very useful. Thanks!
I love MacOS X specially because we can use the best GUI and also a powerful command line tool.