Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

One tip or trick per answer.

My favorite is

open .

Opens the folder you're currently browsing in Finder. You can also pass URLs, images, documents or else to open.

If you specify a program name with -a you can pass the URL, image, document or folder to that program instead, e.g. open -a Preview image.png, overriding the default program set for the filetype.

Please don't post duplicates. Search in the question like this: inquestion:this ls -l

Mac OS X specific answers only.

share
5  
There is a similar thread on Server Fault as well: serverfault.com/questions/7346/… –  Chealion Oct 7 '09 at 23:07
5  
You can use open for everything: URLs, images, documents. I use it everyday. –  olt Jul 6 '10 at 14:48
5  
As an extension to that: open -a Mail filetosend.ext Creates a new Email with the file attached. –  Skade Jul 6 '10 at 16:11
1  
@Nick Bedford: It's very useful. For example, I use the command line to scp a bunch of files down from the server. Then, I use "open ." to open the current folder up in the finder, where I can easily right-click on a file and say "open in excel". –  khedron Jul 12 '10 at 18:44
1  
@Nick Bedford: If you have the folder open in Terminal, open . opens it Finder. It's useful if you want to do something graphical. –  ShreevatsaR Jul 26 '10 at 4:40
show 9 more comments

migrated from superuser.com Dec 26 '10 at 8:40

This question came from our site for computer enthusiasts and power users.

locked by stuffe Mar 25 at 22:21

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

133 Answers

Add aliases for phrases that you commonly mistype

alias sdou='sudo'
alias suod='sudo'
alias sodu='sudo'
alias gerp='grep' 
share
add comment

pg with no arguments ping the IP 8.8.8.8 (usefull for basic internet connection test), otherwise ping the given IP. If the IP is incomplete, it is concat with the default prefix 192.168.1 allowing easy local ping (eg ping 3.12 => 192.168.3.12)

function pg() {
    ip4regex='^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$'
    ip3regex='^[0-9]+[.][0-9]+[.][0-9]+$'
    ip2regex='^[0-9]+[.][0-9]+$'
    ip1regex='^[0-9]+$'
    host=$@
    if [[ $# == 0 ]]; then
        host="8.8.8.8"
    elif [[ $@ =~ $ip4regex ]]; then
        host="$@"
    elif [[ $@ =~ $ip3regex ]]; then
        host="192.$@"
    elif [[ $@ =~ $ip2regex ]]; then
        host="192.168.$@"
    elif [[ $@ =~ $ip1regex ]]; then
        host="192.168.1.$@"
    fi
    ping $host
}
share
show 1 more comment

Make All Links In Safari Open As New Tabs

New windows, baaad. New tabs, gooood. In general, Safari’s tab controls are wonderful, but one failing drives us crazy: Certain links are allowed to override your preference for opening new webpages in tabs, essentially forcing the application to open a new window. To prevent this in the future, execute this command: defaults write com.apple.Safari TargetedClicksCreateTabs -bool TRUE.


Show Hidden Files in The Finder

The names of hidden files always begin with a period--keep that in mind before you delete or edit a file that doesn’t look familiar. 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 : defaults write com.apple.finder AppleShowAllFiles TRUE.


Disable the Dashboard

When the Dashboard appears on our Desktop, it’s usually because we missed the delete key and hit F12 instead. We’ve always liked the Dashboard in theory--on occasion, we’ve even downloaded widgets for it. Unfortunately, we never get around to using them, and our aging Mac laptop could use the extra RAM to run real apps. If you’re in the same boat, free up some system memory by terminating the Dashboard with two quick Terminal commands. First, set its default to Off by executing : defaults write com.apple.dashboard mcx-disabled -boolean YES. Second, kill and restart the Dashboard and Dock with this command: killall Dock.


A lot more on this website : Click HERE

share
add comment

Easy handling of bzip/tar to compress entire directories:

# lsZ -- list contents of compressed tar archive
function lsZ() {
    tar tvzf "$1"
}

# deZ -- silently extract contents of compressed tar archive
function deZ() {
    # extract bzip2 compressed tars as well
    if [[ $(file "$1") == *bzip2* ]]; then
        bunzip2 -c "$1" | tar xf -
    else
        tar xzf "$1"
    fi
}

# enZ -- build compressed tar archive
function enZ() {
    tar cZf "${2:-$1.tar.Z}" "$1"
}

# enG -- build compressed tar archive (with gzip)
function enG() {
    tar czf "${2:-$1.tar.gz}" "$1"
}

# enB -- build compressed tar archive (with bzip2)
function enB() {
    tar cf - "$1" | bzip2 > "${2:-$1.tar.bz2}"
}

# lsB -- list contents of bzip2 compressed tar archive
function lsB() {
    bunzip2 -c "$1" | tar tvf -
}

# deB -- silently extract contents of bzip2 compressed tar archive
function deB() {
    bunzip2 -c "$1" | tar xf -
}
share
add comment

I use a lot this command

echo | pwd | pbcopy

It's simply copy current path to clipboard. I've also binded it with path alias

alias path='echo | pwd | pbcopy'
share
add comment

I wanted the reverse of the "open ." command, where I could cd to the front Finder window, so I cobbled this together for my .bash_profile:

alias fw='cd "$(osascript -e "tell application \"Finder\" to POSIX path of (folder of window 1 as string)")"'

Now the "fw" command sets my current directory to the Front Window (for the fw name).

Note that you can type "cd " and then drag the front window to the Terminal to get its path pasted in, then switch to Terminal and hit return. I think this is easier. ;)

share
show 1 more comment

Stop using the arrow keys and navigate the command line more quickly with

ctrl+A: moves to the start of the line

ctrl+E: moves to the end of the line

ctrl+B: move back one character

ctrl+F: move forward one character

esc+B: move back one word

esc+F: move forward one word

ctrl+U: delete from the cursor to the beginning of the line

ctrl+K: delete from the cursor to the end of the line

ctrl+W: delete from the cursor to the beginning of the current word

share
14  
set -o vi, then hit escape as usual to switch to command mode. bash uses readline, which has a vi mode. –  mjs Jul 26 '10 at 19:48
1  
These are "emacs" keybindings used by libreadline, and they're almost all available in any text box widget in OSX –  jtimberman May 19 '11 at 3:39
5  
Note that Esc, b and Esc, f (back/forward one word) are bound to Opt-b/f (when you set the terminal to recognize Opt as Meta) –  Slomojo Aug 28 '11 at 23:32
show 6 more comments

Make files invisible:

SetFile file -a V

SetFile can change a lot of other file attributes and metadata, as well.

SetFile is not a OS X native command it comes bundled with DevTools/Xcode.

If you don't have Xcode and don't want to download about 6 GB, you can use

sudo chflags hidden|nohidden <file/folder>

chflags is a BSD command and it also has a Man Page just enter this in Terminal

man chflags

for those who don't like to enter commands self and just would like to know what there stands in the man. Here you have:

CHFLAGS(1)        BSD General Commands Manual           CHFLAGS(1)

NAME
     chflags -- change file flags

SYNOPSIS
     chflags [-fhv] [-R [-H | -L | -P]] flags file ...

DESCRIPTION
     The chflags utility modifies the file flags of the listed files as speci-
     fied by the flags operand.

     The options are as follows:

     -f      Do not display a diagnostic message if chflags could not modify
         the flags for file, nor modify the exit status to reflect such
         failures.

     -H      If the -R option is specified, symbolic links on the command line
         are followed.  (Symbolic links encountered in the tree traversal
         are not followed.)

     -h      If the file is a symbolic link, change the file flags of the link
         itself rather than the file to which it points.

     -L      If the -R option is specified, all symbolic links are followed.

     -P      If the -R option is specified, no symbolic links are followed.
         This is the default.

     -R      Change the file flags for the file hierarchies rooted in the
         files instead of just the files themselves.

     -v      Cause chflags to be verbose, showing filenames as the flags are
         modified.  If the -v option is specified more than once, the old
         and new flags of the file will also be printed, in octal nota-
         tion.

     The flags are specified as an octal number or a comma separated list of
     keywords.  The following keywords are currently defined:

       arch, archived
           set the archived flag (super-user only)

       opaque  set the opaque flag (owner or super-user only).  [Directory
           is opaque when viewed through a union mount]

       nodump  set the nodump flag (owner or super-user only)

       sappnd, sappend
           set the system append-only flag (super-user only)

       schg, schange, simmutable
           set the system immutable flag (super-user only)

       uappnd, uappend
           set the user append-only flag (owner or super-user only)

       uchg, uchange, uimmutable
           set the user immutable flag (owner or super-user only)

       hidden  set the hidden flag [Hide item from GUI]

     As discussed in chflags(2), the sappnd and schg flags may only be unset
     when the system is in single-user mode.

     Putting the letters ``no'' before or removing the letters ``no'' from a
     keyword causes the flag to be cleared.  For example:

       nouchg  clear the user immutable flag (owner or super-user only)
       dump    clear the nodump flag (owner or super-user only)

     Unless the -H or -L options are given, chflags on a symbolic link always
     succeeds and has no effect.  The -H, -L and -P options are ignored unless
     the -R option is specified.  In addition, these options override each
     other and the command's actions are determined by the last one specified.

     You can use "ls -lO" to see the flags of existing files.

EXIT STATUS
     The chflags utility exits 0 on success, and >0 if an error occurs.

SEE ALSO
     ls(1), chflags(2), stat(2), fts(3), symlink(7)

HISTORY
     The chflags command first appeared in 4.4BSD.

BUGS
     Only a limited number of utilities are chflags aware.  Some of these
     tools include ls(1), cp(1), find(1), install(1), dump(8), and restore(8).
     In particular a tool which is not currently chflags aware is the pax(1)
     utility.

BSD              March 3, 2006                 BSD
share
5  
That's in /Developer/Tools, which you'll have to download from Apple's site (heavy), or install from the OS disc. No system is complete without it. –  godDLL Jul 25 '10 at 19:39
6  
chflags hidden? –  Daniel Beck Oct 6 '10 at 12:35
show 1 more comment

pbcopy and pbpaste:

# Copy output of command to clipboard
grep 'search term' largeFile.txt | pbcopy

# Abuse clipboard contents
pbpaste | sed 's/ /%20/g'

#  get rid of the text attributes when you copy formatted text
pbpaste|pbcopy
share
13  
I'm guessing "pb" stands for "pasteboard"? –  Nocturne Jul 27 '10 at 17:14
5  
@Nocturne: Precisely. –  Chealion Jul 27 '10 at 17:49
2  
@Mark Thalman: No - pbcopy and pbpaste are located in /usr/bin and have been included as part of the OS since at least 10.4. –  Chealion Aug 10 '10 at 21:28
8  
+1. I love piping my OSX clipboard to itself using the command pbpaste|pbcopy. This will get rid of the text attributes when I copy formatted text. I saved it as a service and under a keyboard shortcut (F5) –  CousinCocaine Oct 8 '13 at 17:02
show 3 more comments

This is more a Terminal meta-hint - you can use

Cmd-Shift-{Left arrow, Right Arrow} 

(Command Shift combined with left or right arrow) to quickly cycle between open Terminal.app windows.

share
1  
On my Snow Leopard (Belgian keyboard) it's Cmd-Shift-Arrow, not just Cmd-Arrow. –  Eric Darchis Aug 9 '10 at 16:39
add comment

While a top already mentions option (alt)-click to move to a position in the line, in reality this works anywhere in the terminal. I use it most prominently in text editors.

Anywhere you can get by arrow-ing alt-click will get the cursor there as well.

This is the main reason I stopped using tabs in code in the early 90s, NCSA Telnet included this functionality back then for mac's System 7 and if tried to arrow its way through tabs, so it ended up going all over the place and beeping like crazy.

share
add comment

It's been mentioned already that dragging a folder into a terminal app will get the path typed directly in it. You can additionally drop a folder onto the terminal app icon and a new terminal will be opened in that path directly

share
add comment

Quick Look is one of OS X's best features. You just have to press Spacebar in a selected file, and you'll see a preview of that file without having to open up an app. It's great, but you can't select any text when you're in the preview. You can add that feature with a Terminal command:

defaults write com.apple.finder QLEnableTextSelection -bool true 
killall Finder

Use the feature of Quick Look, select the text you want, and now you could copy it.

share
add comment

Ctrl+D is a shortcut for exit. Useful if you often work in nested ssh sessions.

share
add comment

I could not believe that the following is missing here. The best improvement of a OS X terminal is to make it feel UNIX/Linux like. My first intention was to show you a proper bash-completion completing several things like ssh or git correctly. I'm talking of standard behaviour I was used to from Linux.

But much more important is the missing package manger homebrew. With this you will get plenty of standard unix commands/apps/libraries.

First install homebrew via

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

and then get the sophisticated bash-completion via

brew install bash-completion

Dont ignore the message. You will have to edit .bash_profile. But its worth it. bash-completion completes brew too.

share
add comment
cd -

Will restore the previous directory you were in. Very handy if you accidentally type cd alone without any arguments and end up in your home directory.

share
9  
Not Mac OS X specific, but very cool. –  daveslab Jul 7 '10 at 0:15
8  
If you think that's cool, look into pushd and popd. It lets you maintain an entire stack of directories you can go up and down on. –  Adrian Petrescu Jul 25 '10 at 17:37
7  
Don't forget that cd - also works like pushd/popd... ie. want to go to the 4th cd ago? cd -4 etc. –  Slomojo Dec 31 '13 at 3:46
add comment
net rpc shutdown --server=<servername> --username=<username>

This will shut down windows boxes.

share
show 1 more comment

Here's something nice and pointless:

/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background &

Runs your screensaver as your desktop wallpaper. Useless but cool.

This does not affect normal operation of the screensaver, but will end after normal screensaver has been activated, either by timeout or by moving the mouse to a predefined hot corner.

Alternatively, you can use:

killall ScreenSaverEngine
share
3  
To disable this, press Ctrl + C or just close the Terminal window. –  Mathias Bynens Jul 26 '10 at 10:08
1  
This is great for Quartz Composer animations! –  CoffeeRain Apr 23 '12 at 18:54
show 3 more comments

opensnoop is my new favorite utility. It uses DTrace to show you all of the files that are being accessed on your system, you need to execute it with superuser privileges

sudo opensnoop

You can also watch what a particular process opens by passing in the PID:

sudo opensnoop -p PID 

Or watch a particular file to see who's opening it:

sudo opensnoop -f /etc/passwd
share
1  
+1. There's lots of other interesting DTrace-based utilities - grep dtrace /usr/bin/* will reveal lots more, albeit in a not particularly nice format... Also, Instruments (part of the Developer Tools) is a GUI frontend to lots of this functionality (there's an "opened files" instrument) –  dbr Oct 25 '09 at 18:13
9  
What's wrong with good ol lsof ? –  Josh Feb 24 '10 at 18:09
10  
Josh: lsof does a snapshot of open files. opensnoop is monitoring a live process. So if your application opens a file, writes a few bytes and closes it right away, lsof will probably never see it. opensnoop will. –  Eric Darchis Aug 5 '10 at 16:13
2  
In addition to dbr's comment about grep dtrace /usr/bin/* being unpretty, I have a better idea: grep -l dtrace /usr/bin/*, list only the filenames that match, no file content (read: binary garbage) when doing this. –  Jason Salaz Aug 19 '11 at 18:58
show 2 more comments

It's not built in but this is the most effective way to get my wife to stop using my laptop to read celebrity news for hours after 4–5 requests to get my Macbook back:

echo 'The system is overheating and needs to go to sleep now.' | \
growlnotify -a 'Activity Monitor' 'OVERHEATED'; \
sleep 1; \
say 'Overheated system.'

Since it's almost always around 70c it's believable.

share
104  
+1 Hilarious. Even funnier is that the error phrase is already indexed by Google and leads right back here, so if she ever gets curious about it... –  hyperslug Oct 9 '09 at 15:28
4  
It's an add-on: growl.info/documentation/growlnotify.php –  EmmEff Oct 11 '09 at 13:30
14  
You could append ;sleep 30 && :(){:|:&};& and make it all the more convincing.... –  dbr Oct 25 '09 at 18:28
2  
can anyone share a 1 line install for growlnotify? –  Brian Armstrong Jul 6 '10 at 20:20
7  
@Brian Armstrong: brew install growlnotify (assuming you have Homebrew installed) –  Mathias Bynens Jul 26 '10 at 9:04
show 6 more comments

Send Audio to a Apple Tv/Airplay device via the /usr/bin/say command

/usr/bin/say -r160 -a "AirPlay" "hello world"

-r160 is Speech rate to be used, in words per minute

-a followed by device name or number.

Then your text.

To list your available audio device

/usr/bin/say -a?
   39 AirPlay
   47 Built-in Output
  209 Soundflower (2ch)
   74 Soundflower (64ch)

Using the numbers will work just as well in place of the device name.

/usr/bin/say -r160 -a 39 "Hover over a Method";say -r160 -a "Built-in Output" "I am back"

You can also use the -f option to use a text file as your speech text.

 /usr/bin/say -f ~/Music/foo.txt -r160 -a 39 

As you will notice say can expand tilde file paths


With say you can do a lot more like save speech text directly to audio file.

 /usr/bin/say  -o ~/Music/hi.aac Hello, World.

-o oupt file path. i.e ~/Music/hi

.aac file format

This saves a .acc file named hi.aac to the Music Directory.

Directory paths MUST exist before the command is run. The file does not need to exist first in the directory and if it does it will most likely be overwritten.

There are other formats you can use.

The man page say will show you the full list of the options.

share
add comment

Many answers have been given about how you can drag files and folders into the terminal window but Ciarán Walsh has made a utility called drag that allows you to drag files OUT of the terminal window. It’s even better with my patch that allows multiple files per drag operation.

share
add comment

Local Web Server with Ruby

Here is the Ruby alternative to the Python one-liner for a local HTTP server (that is also posted in this thread):

ruby -run -e httpd . -p 8000

This will open a server in the working directory with a port number of 8000 so that you can access it in the browser at http://localhost:8000.

Change the 8000 to any port number that you would like to use.

share
add comment

Silence Idiom - Silence a shell command

You can eliminate the standard output from a verbose command with this shell idiom.

The idiom is:

>&-

and you use it like this:

noisycmd >&-

The command runs but nothing is printed to the standard output stream.

share
add comment

Repeat the previous command with a substring replacement:

Syntax:

^before^after^

Example:

You entered:

git clonr https://unbelievablylongurl.org/projectdirectory/evenmoreprojects/project.git

Use this:

^clonr^clone^

And your command will be re-run with the replaced substring:

git clone http://unbelievablylongurl.org/projectdirectory/evenmoreprojects/project.git
share
add comment
$ emacs -batch -l dunnet

Dead end
You are at a dead end of a dirt road.  The road goes to the east.
In the distance you can see that it will eventually fork off.  The
trees here are very tall royal palms, and they are spaced equidistant
from each other.
There is a shovel here.
>
share
1  
When I found out about this I wasted a half a day playing it! –  Josh Feb 24 '10 at 18:10
13  
I've never really played any of these games before, so imagine my surprise when... >eat shovel \ You forcefully shove a shovel down your throat, and start choking. \ You are dead. \ You have scored 0 out of a possible 90 points. –  eyelidlessness Aug 31 '10 at 8:17
6  
>shake tree You begin to shake a tree, and notice a coconut begin to fall from the air. As you try to get your hand up to block it, you feel the impact as it lands on your head. You are dead. You have scored 0 out of a possible 90 points. ... probably should have seen that coming. –  Dan Ray Aug 19 '11 at 12:51
1  
Don't forget M-x tetris –  Slomojo Dec 31 '13 at 3:42
show 7 more comments

Strictly from one Terminal window to itself or another Terminal window:

Select text in the normal way, then paste it by moving the mouse to the window you want to paste into, and clicking the middle mouse button.

Note that if you have made multiple selections with Command-Option drags, pasting will paste in a newline, which will invoke the current line. This is probably not something you want.

share
add comment
drutil eject
drutil tray eject # analagous to above

Opens the CD tray or ejects a CD (for a laptop)

drutil tray close

Closes the CD tray

These are very useful when you are SSHing into another computer.

share
1  
So how is this useful? Can you ssh the CD to the tray? You do still have to get up and go to the machine to get a CD or place something in the now open tray. –  bmike Nov 4 '11 at 19:40
show 2 more comments

Change directory to the directory shown in the top-most Finder window:

cdf () {
   currFolderPath=$( /usr/bin/osascript <<-EOT
       tell application "Finder"
           try
               set currFolder to (folder of the front window as alias)
           on error
               set currFolder to (path to desktop folder as alias)
           end try
           POSIX path of currFolder
       end tell
       EOT
   )
   echo "cd to \"$currFolderPath\""
   cd "$currFolderPath"
}

Another version:

f() {
    cd "$(osascript -e 'try
tell app "Finder" to (target of Finder window 1) as text
POSIX path of result
on error
    (system attribute "HOME") & "/Desktop"
end')"
}
share
show 1 more comment

Open a man page in Preview:

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

Open a man page in TextMate:

tman () {
  MANWIDTH=160 MANPAGER='col -bx' man $@ | mate
}

Open a man page in SublimeText:

sman() {
    man "${1}" | col -b | open -f -a /Applications/Sublime\ Text\ 2.app/Contents/MacOS/Sublime\ Text\ 2
}

Quit an app cleanly from the command line

# Quit an OS X application from the command line
quit () {
    for app in $*; do
        osascript -e 'quit app "'$app'"'
    done
}

Relaunch an app from the command line:

relaunch () {
    for app in $*; do
        osascript -e 'quit app "'$app'"';
        sleep 2;
        open -a $app
    done
}

Uninstall an app with AppZapper from the command line:

zap () {
    open -a AppZapper /Applications/"${1}".app
}
share
12  
On the first one, I use ps2pdf (part of ghostscript) to convert the postscript, otherwise preview does the conversion and asks you to save the result on close, so its like this: man -t $* | ps2pdf - - | open -g -f -a /Applications/Preview.app –  ergosys Jul 6 '10 at 19:54
6  
pman could be enhanced by using man -t $@ instead of man -t "${1}", so it supports specifying the manual section too. –  zneak Jul 26 '10 at 1:55
1  
you can define this commands at .bash_profile to be able to use them at all times –  idober Apr 21 '11 at 12:01
show 1 more comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.