
OS X Command Line Utilities - AlexeyBrin
http://www.mitchchn.me/2014/os-x-terminal/?x
======
reuven
This article was nice, but it indicated that you need to change the system
preferences in order to change the voice. It turns out that you can pass the
-v flag to use a different voice, or "-v ?" to get a list of names.

So you can do

    
    
        say -v Samantha Help, I'm trapped in this castle!
    

or

    
    
        say -v Princess Help, I'm trapped in this castle!
    

But wait, it gets even better: The Mac comes with a number of voices for other
languages, such as French, Hebrew, Chinese, and Arabic. And it turns out that
the voices will work in English as well, _using that country 's accent_. I
just tried it with a few different languages, and was amazed by how well this
worked, within reason:

    
    
        say -v Sin-ji  "Hello, I am Chinese.  What do you want to eat?"
        say -v Thomas  "Hello, I am French.  What do you want to eat?"
        say -v Carmit  "Hello, I am  Israeli.  What do you want to eat?"
    

And yes, I _should_ get back to work...

~~~
nyc640
Another fun one:

    
    
        say -v cellos dum dum dum dum dum dum dum he he he ho ho ho fa lah lah lah lah lah lah fa lah full hoo hoo hoo
    

Edit: 'In the Hall of the Mountain King' if anyone is curious.

There is also 'Pomp and Circumstance':

    
    
        say -v Good dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum
    

and Chopin's 'Funeral March':

    
    
        say -v Bad dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum dum

~~~
sal_paradise
And yet another:

    
    
       say --voice='?' | perl -lane 'my $v = $F[0]; system("say -v $v \"Hi $ENV{'USER'}\"")'

~~~
nxpnsv
Or just stay in the shell...

    
    
       for voice in `say --voice="?" | awk '{print $1}'`; do say -v $voice "Hello $USER, I'm $voice"; done

------
rjeli
pbpaste and pbcopy never really occur in ambiguous situations, so I wrote the
following shell script:

    
    
      function clip { [ -t 0 ] && pbpaste || pbcopy }
    

This is easier to type and allows for the following:

    
    
      % echo hello | clip
      % clip
      hello

~~~
kbd
> function clip { [ -t 0 ] && pbpaste || pbcopy }

That's great! Would you please explain why that works? Are there any cases you
know of where that doesn't work as expected?

Edit: btw you need a semicolon after pbcopy to make that function valid on one
line.

~~~
godDLL
I'm not the OP, but I'll give it a go.

`[` is a Bash built-in command also known as `test`. The `-t` parameter tells
it to test if a file descriptor is open for `0`, which is also known as
`STDIN`.

So if you're piping something into `STDIN` it will do `pbcopy`. If not -- it
will do `pbpaste`.

------
chimeracoder
For Linux users, `xdg-open` is the equivalent of `open`. The latter exists on
Linux, but it will open a socket.

There are a number of utilities that handle copy/paste, but `xclip` is
probably the most widely used.

Screenshots can also be done a number of ways, but `scrot` is my favorite. The
two most useful flags to pass with it are `-s` and `-d`.

As for `launchctl`, `systemctl` is what you want to use to do the same things.

Note that these equivalents all address the same functionality, but the syntax
may be different.

~~~
pimlottc
Having discovered the usefulness of pbcopy/pbpaste on OSX, I'm simply amazed
that the equivalent X utilities are not included by default on every major
Linux distribution.

~~~
gh02t
Different philosophy, partly motivated by the consideration that with a
package manager the barrier to installing it really low. Personally I prefer
to have as little installed as possible in the base system so that I can pick
and choose what I want on top. Metapackages that install a large selection of
stuff or distros that ship a ton of stuff by default drive me crazy. I don't
mind it so much on a Mac as that's kind of part of the whole philosophy of OS
X, but Linux (and friends) are in a different niche for me.

I'm sure some desktop distros do ship xclip by default though. Knowing the
typical variety of Linux distros I expect there's probably even an Xclipbuntu,
dedicated solely to showing off the latest xclip release (the users of which
have a decade long feud with Xseldora).

~~~
pimlottc
I guess I should say I'm more surprised that something like xsel or xclip is
not part of the standard x11-utils or what have you.

~~~
gh02t
Oh yeah, I agree. Pretty sure the reason xsel or xclip isn't in x11-utils is
that they are not part of the Xorg project. Obviously something with
equivalent functionality _should_ be there, but I guess the Xorg folks
overlooked it and packagers don't want to stick in random stuff.

------
cstross
A key command is missing: textutil.

textutil is a general purpose front end to the core text engine and is one of
the cleanest docx-to-html converters I've run across, with a bunch of file
formats supported and charset encoding translations, metadata manipulation
commands, and assorted juicy goodness for people who have to mess with word-
processed text.

Ironically the only common-on-Apple document format it can't do anything with
is that of Apple's Pages word processor ...

~~~
Steuard
The followup post (evidently this was from last year) credits you with that
addition.

(I was surprised by the lack of support for Pages, too.)

------
guan
I would add caffeinate, which prevents the Mac from going to sleep. It can do
this indefinitely, for a fixed period of time, or after a process is done
running. You can even specify that process either as the PID of an existing
process or by invoking it through caffeinate itself.

~~~
lukeholder
Recommend "Amphetamine" as an alternative. More features and kept up to date
with bug fixes and improvements. I am not affiliated, just a happy user.

~~~
jason_slack
Can you explain why one might use this, versus just setting the machine to not
sleep in System Preferences, in combination with not turning off hard disks,
etc?

I still set my display to sleep, however. Am I missing something?

~~~
pavel_lishin
You may want your machine to go to sleep normally - e.g., when you leave it on
your desk at home and go to sleep - but not when you're at a hackathon, and
are running some process while you go and get a snack, or are presenting a
video that requires no actual input from you.

~~~
jason_slack
ah, I see, a `selective` sleep. Makes sense, I am going to check this out.
Thank you.

------
balls187
`say` is one of my favorite little things about OS X. In a couple of my build
script, I have throw in a couple random say commands if say is installed on
the system. Everyonce in a while a Dev will ping me when their computer speaks
to them.

I created a gist that says a random starwars quote in each of the systems
supported voices.

[https://gist.github.com/balasuar/6bf1c64594780836cfcd](https://gist.github.com/balasuar/6bf1c64594780836cfcd)

~~~
x0x0
I use it for reminders, too -- eg

    
    
        sleep 240 && say "tea done"
    

so I don't over steep my tea

------
tammer
This is a great intro. Here's my favorite OS X Terminal trick:

⌘. (command period) is a hotkey not defined in the menu for sending BREAK.
This is automatically equivalent to ctrl+c in shells, ctrl+g in emacs and ESC
in Vim. Similarly, ⌘K is short for clearing the screen. These are much more
ergonomic than the standards on Mac laptops and wireless keyboards.

~~~
apas
How is cmd + K different from cmd + R and/or $ clear?

~~~
osxosxosxosxosx
Using ⌘+K will not only clear the screen, but will also delete the scrollable
history buffer in Terminal or iTerm2.

I find this useful before printing text that I want to search using ⌘+F.

------
JoachimS
I can recommend using iTerm2 as the command line app. Apples Terminal has
improved. But iTerm2 has a lot of handy features. A great terminal.

[https://www.iterm2.com](https://www.iterm2.com)

------
alangpierce
One nice application I've found of pbpaste is when I want to count things I
find in a browser. For example, to count the (approximate) number of comments
in this thread, you can copy all text using Cmd+A, Cmd+C, then run this:

pbpaste | grep ago | wc -l

In this case there are easier (and more accurate) ways, but in other
situations you can use it to find the length of a list on the web where it
would otherwise be harder.

~~~
emmelaich
pbpaste | grep -wc ago

is 0.3% faster and 1.7% more correct :-)

------
reubenmorais
And if you'd like to use some of those utilities on GUI apps, don't forget the
utility to bind them all: Automator.app. It'll let you interact with terminal
and GUI apps in all sorts of interesting ways. For example, you could create a
global keyboard shortcut to upload the selected text to a pastebin.

------
natch
Remove unwanted formatting from text in the clipboard:

    
    
        alias pbclean='pbpaste | pbcopy'

~~~
dllthomas
I wrote "write the clipboard to a temp file; open it in vim; when vim exits,
if the temp file has been written, load it into the clipboard". Pretty
convenient.

Also, (though not, I think, relevant to OS X), binding a key to move content
between PRIMARY and CLIPBOARD on X Windows has been very nice.

~~~
endymi0n
Not exactly memorable, but glad that I discovered it eventually: "Shift +
Option + Command - V" = Paste as Plaintext.

------
revicon
I'm surprised they didn't mention anything about the command line utilities to
manage the mac's airport (scan for wireless networks, list network interface
names, etc). I did a quick blog post about these a while back:
[http://blog.mattcrampton.com/post/64144666914/managing-
wifi-...](http://blog.mattcrampton.com/post/64144666914/managing-wifi-
connections-using-the-mac-osx)

~~~
egwor
my airport time machine backup often hangs and I have to restart the machine
(via airport utility). I wonder... is there a way to tell it to restart via a
similar type of command?

------
jmount
A nice complement to the command line "open" command is adding a shell
launcher to OSX finder. I have some instructions how to do this here:
[http://www.win-vector.com/blog/2012/05/enhance-osx-finder/](http://www.win-
vector.com/blog/2012/05/enhance-osx-finder/)

~~~
odbol
Oh wow I've been looking EVERYWHERE for that. Thanks so much!

Also, a tip: an easier way to change the icon of any app/folder/anything:

1\. Right click it -> Get Info.

2\. Drag an app that has the icon you want onto the icon in top-left of the
Info window. (e.g. drag the Terminal.app into the Info window and drop it on
the icon: that script will now have the same icon as the Terminal.)

------
mattdesl
Nice commands. Also 'sips' for batch resizing images.

If you aren't on OSX you can try the following for a simple 'say' alternative.
It has some great robotic/singing voices, too.

[https://github.com/Jam3/says](https://github.com/Jam3/says)

------
danso
This was posted last year and did very well on HN [1]. I remember because it
is literally the thing that got me interested in using the command-line as a
power user...I'm embarrassed to say I hadn't really understood piping, but
curling texts from Gutenberg into `say` was a fun introduction. Now I
constantly use open, pbpaste, and pbcopy... learning about screencapture was
also extremely helpful for my blogging and tutorial writing, as I've written a
few wrappers around it to customize and optimize its output, including auto-
uploading it and creating a snippet I can quickly paste into a blog post.

Great list!

[1]
[https://news.ycombinator.com/item?id=7747982](https://news.ycombinator.com/item?id=7747982)

------
fensipens
say -v cellos "Dum dum dum dum dum dum dum he he he ho ho ho fa lah lah lah
lah lah lah fa lah full hoo hoo hoo"

:)

~~~
drjeats
:)

I have a little local deploy script that runs this if it fails a smoke test:

say -v Bad "Deployment failed, server gave a bad response"

------
wanderfowl
I have fond memories of discovering my college roommate's open SSH connection,
and using "say" to great effect.

~~~
gaius
Back in the day you'd "telnet" into your friend's "Sun workstation" and cat an
"aiff" to the "/dev/audio". How times have changed! :-)

~~~
garthk
The Sun 3/50's pixel buffer was world readable and writable by default, and in
console mode had an area at the bottom not affected by scrolling. One could
invert random horizontal bars across the screen, transpose the bitmap, or
apply a sine wave to persuade the user the massive TV set on top of their
workstation was broken. Or, fade text in and out as if the machine was
commenting on the user's ineptitude. Much fun was had by all.

------
_paulc
The first of these is easier as:

    
    
      open -a Safari

~~~
rattray
Agreed, I often use `open -a 'Google Chrome' ./index.html` or `open -a 'Google
Chrome' [http://0.0.0.0:8000`](http://0.0.0.0:8000`)

~~~
algorithms
I do the same so I aliased it to just "chrome", "firefox", etc.

~~~
lukeadams
I aliased Sublime to `sub`. Without args it opens the current folder as a
project; with args it opens the file[s].

~~~
Zarel
The officially-supported name is `subl`, by the way:

[https://www.sublimetext.com/docs/2/osx_command_line.html](https://www.sublimetext.com/docs/2/osx_command_line.html)

~~~
lukeadams
Huh. I clearly didn't research before I wrote my one-liner. This is certainly
a little more ... documented. Thanks for the heads up!

------
fmela
mdfind also has a -name option that allows one to search for the query in the
filename rather than contents.

------
dljsjr
Does anybody know of a good alternative to "at" on OS X? I know it's there but
not enabled by default, I went through the paces required to activate it long
ago but it something in Yosemite seems to have broken atrun and I can't find
anything about it anywhere online.

~~~
protomyth
Works for me. I would do an unload then load to see if it got messed up in the
upgrade Yosemite.

    
    
      sudo launchctl unload -F /System/Library/LaunchDaemons/com.apple.atrun.plist
    
      sudo launchctl load -F /System/Library/LaunchDaemons/com.apple.atrun.plist
    

[edit: maybe check /var/at/at.allow]

------
tlrobinson
Also dtrace and some of the included scripts like opensnoop are awesome.

------
mirkules
Great list, some really useful commands.

One question: What's wrong with "locate"? It is really fast because the file
system contents are indexed. As long as you understand that it's not going to
pick up the latest new files without running "updatedb"
(sudo/usr/libexec/locate.updatedb" in os x) first, it's much better than find
if you're doing a quick search.

However, I didn't know spotlight has a CLI. Cool.

~~~
skygazer
I prefer mlocate to locate, as it rebuilds the index in a flash by diffing and
by paying attention to modification dates when traversing, so you can run its
updatedb more frequently without a noticable penalty.

That said, mdfind is terrific -- it's index is, as you suggested, always upto
date, and it doesn't just index file names, but also content.

~~~
senderista
I like to use mdfind for ack-style search over my whole system:
[https://gist.github.com/senderista/1246300](https://gist.github.com/senderista/1246300)

------
salgernon
Oftentimes I'll have something on the clipboard, so pbpaste | grep is good.
But sometimes the thing I want to search for is long, such that I don't want
to type it for the grep.

Fortunately, pbpaste takes a -pboard flag for selecting a different buffer. So
cmd-e some text to put it on the find pasteboard, then 'pbpaste | fgrep
--color -i "`pbpaste -pboard find`"'

I usually have this aliased to 'pbg'

------
contingencies
Sadly Xcode3's excellent merge tool seems inaccessible from the command line
in Xcode4. Anyone have a fix?
[http://stackoverflow.com/questions/13163670/how-to-use-
xcode...](http://stackoverflow.com/questions/13163670/how-to-use-
xcode-4-mergetool-in-a-standalone-fashion)

~~~
super_mario

        opendiff file1 file2
    

will invoke the merge tool.

~~~
jfb
It's also the default for git mergetool.

------
baldfat
Non-case sensitive really bothers me with OS X

~~~
makecheck
This is not actually an OS limitation, it is a default filesystem choice. The
Mac supports multiple types of filesystems, including case-sensitive ones.

Having said that, I wouldn't reformat your boot drive to be case-sensitive
because this isn't a common configuration and I'd expect 3rd-party apps to
have problems.

What you _can_ do is use Disk Utility to create a case-sensitive file system
on a disk image, which gives you case-sensitive behavior when you really want
it (and limited to activities on that disk).

~~~
baldfat
Thank you I didn't know this. Then I will again asked why Apple is STILL on
HFS+? If they actually moved to ZFS or any modern file format it really would
help the developers world. Just seems that this is such a obvious need to be
fixed that doesn't get any concern form Apple and most users/developers.

~~~
makecheck
I'm not sure if there is an official explanation but a pretty good analysis of
it is in John Siracusa's review of OS X 10.7 (Lion):

[http://arstechnica.com/apple/2011/07/mac-
os-x-10-7/12](http://arstechnica.com/apple/2011/07/mac-os-x-10-7/12)

[http://arstechnica.com/apple/2011/07/mac-
os-x-10-7/13](http://arstechnica.com/apple/2011/07/mac-os-x-10-7/13)

------
delinka
"Many a Linux power user has tried to use locate to search for files on a Mac
and then quickly discovered that it didn’t work."

Rather, that it gives you instructions for getting it to work. How's a Linux
power user getting by without following such instructions to turn on one of
their favorite utilities?

------
hmottestad
I use: open vnc://myServer.local

It will open up the screen sharing app and connect for you :)

~~~
iamdave
One of my favorite tricks when I learned it, because I was already in the
terminal, no need to reach over for the mouse to remote into a wallboard via
screen sharing.

------
raldi
Paging mods for headline change. I suggest, "OS X Command Line Utilities"

~~~
ikurei
I would also change it, but your suggestion doesn't indicate if this is a
comprehensive manual or a short introduction, apt for only-midly-technical
folks.

I don't know if it would be worth the effort to enforce a more complete set of
title guidelines, but having better titles would be nice.

------
ss64
I've documented many of these utilities here:
[http://ss64.com/osx/](http://ss64.com/osx/)

~~~
melloc
Thank you for your site! When I first started using the shell, I found it
useful for discovering new utilities. I still use it whenever I find myself on
Windows and needing a cmd equivalent. :)

------
SG-
Anyone happen to know how he's getting archey output to be colour for the
Apple logo? my iTerm and Terminal is just in white/black.

~~~
iamdave
Probably using an alternate shell like zsh

~~~
Watabou
bash (and others) can show terminal colors just fine, terminal colors are not
zsh specific.

------
kuon
There is also `tmutil` to manage time machine backups, can be handy,
especially in scripts.

------
FilterSweep
#6 is the likes of what got us detentions in middle school

------
tomphoolery
The "alphabetical list of all OS X commands" page this article links to is
cute. :)

------
flippant

        say 'ay ay. ay ay. smoke weed. every day.'

------
benihana
I like do harmless pranks on coworkers who don't lock their computers

    
    
        yes "lock your computer, numbskull" | xargs say
    

Just repeats the phrase in a monotone computer voice over their headphones. I
only do this to engineers, tried it on a PM once, never again.

~~~
melling
Have you ever asked yourself if maybe you're just being annoying? I don't lock
my computer. It'll time out and lock after an hour but I prefer to leave it
unlocked.

~~~
akerl_
That's pretty terrible opsec. It presents a risk to separation of roles /
compartmentalization if a coworker can walk over to your workstation and have
access to it, to say nothing of malicious access by somebody who shouldn't be
in the office in the first place.

~~~
matwood
If locking your computer in the office is required opsec, then you have
already lost. First, you shouldn't have random people walking around the
office. Once someone has physical access the battle is already over. Second,
rogue employees are still rogue employees, and an unlocked computer is the
least of your worries.

With that said, I always lock my computer out of habit.

~~~
mentat
Not sure what size company you're working in nor what the requirements for
opsec are their nor your privilege levels but it certainly does not mean you
have already lost.

------
scrollaway
What's with all the buzzfeed-level headlines making HN frontpage the past few
days?

Not to say this isn't a useful list (for OSX users that is), but I can't
possibly be the only one weirded out by this.

~~~
dang
> buzzfeed-level headlines making HN frontpage the past few days

This is most likely random fluctuation a.k.a. sample bias, but if you know of
any that didn't get corrected, please email them to us at hn@ycombinator.com
so we can figure out why.

People post such titles all the time but we change them systematically. For
example, we changed this one shortly after your comment. Normally we'd have
replied to your comment then; probably the moderator didn't see it.

Users not in North American time zones do see more baity titles, though. We
cover as broad a span of hours as we can, but it isn't 24.

~~~
scrollaway
Thanks - no, they all got corrected, you guys do great work :)

I think it's sample bias as well, just struck me because I rarely ever saw it
before. Probably _because_ they all get corrected very quickly.

------
jd3
Great list, not a big fan of homebrew personally, or its creator who seems to
be full of himself. I'd recommend pkg_src from joyent[0]. homebrew seems to
have a lot of the hip webdev packages, but pkg_src and joyent's repository is
the real deal when it comes to hardcore UNIX package management. Some friends
have a nice bootstrap for pkg_src on OS X called saveosx[1], too.

[0]: [https://pkgsrc.joyent.com/install-on-
osx/](https://pkgsrc.joyent.com/install-on-osx/)

[1]: [http://www.saveosx.org/](http://www.saveosx.org/)

~~~
riffraff
FWIW, I have no issues with homebrew, but I have used macports for many years
and never had any issue. Especially now that it supports binary packages, I
find it perfect for my usage.

~~~
brobinson
I had tons of issues with macports over the years (e.g., emacs port was broken
for months after 10.6 came out), but I think that was mostly a function of its
smaller userbase and more difficult contribution system. Homebrew seems to
have many more users and a far simpler way to contribute, so it's rare that I
encounter a broken or old package.

------
lewisjoe
I'd like to someday ssh into somebody's computer; run `say` with creepy texts.
JFF.

~~~
donatj
Years ago at my old office we had a G4 tower that no one used. I set up SSH on
it so I could use it for long running tasks without slowing down my local
machine.

A coworker was on it doing the rare at the time Safari testing - usually only
on client request. I sshed into it and ran 'say "Help, I'm stuck in the
computer"'. My coworker was very very confused and I was cackling to myself.
He still talks about it to this day.

------
mistersquid
As a longtime Mac user (as early as System 7) and aficionado of UNIX, I love
OS X's CLI and its affordances. The linked article provides several well-
packaged tidbits that might encourage users of other CLI-replete OS's to check
out OS X.

More power.

However, I'm not a fan of the soft recommendation for Homebrew. I understand
Homebrew places everything in `/usr/local` but software installs on Mac should
generally conform to dragging and dropping bundles inside `/Applications`.

In my experience, requirements to install packages using Homebrew could be
circumvented by searching for .dmg or .pkg equivalents. The benefit is that
software so installed is much easier for intermediate users to track and
maintain.

~~~
joesmo
I think MacPorts is a much better tool than Homebrew with way more useful
packages. It also installs itself into /opt/local by default so it doesn't
conflict with other stuff in /usr/local and for actual OS X or X-Windows apps,
it installs them in /Applications. Luckily, they can both live on one system
if you're careful, as some people insist on providing only Homebrew copies of
their software, which is a bit unfortunate considering that MacPorts is
clearly the better system.

~~~
Alphasite_
I found home-brew much more problematic and more significantly much slower
when i last used it (a few years back now).

~~~
stephenr
At this point I've given up on any of these "package managers" for OS X.

I've thought about starting a project (possibly with some support from my
company, which focuses on Linux packaging) to provide a) a tool to download
and install .pkg files, and b) a toolchain for more easily building .pkg files
for the things that aren't available.

