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

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.

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

133 Answers 133

Function to make a directory and cd into with a single command:

function take {
    mkdir $1
    cd $1
}
share
8  
Better: mkdir -p $1, since this allows creating nested new directories. And putting a && between the commands will only execute cd if the folder was successfully created. –  Konrad Rudolph Jul 25 '10 at 18:02
show 1 more comment

open all results of find in a single textmate window:

find . -name "pattern"|xargs mate

also works with mdfind (spotlight):

mdfind -name models.py |xargs mate
share
show 1 more comment

Download a URL to the current dir with curl.

curl -O http://growl.cachefly.net/Growl-1.2.1.dmg

Especially good for downloading source tarballs that Safari wants to decompress for you.

share
show 1 more comment

Get terminal to open in the last visisted folder:

I have longed to get terminal to open in the last visited folder, and ended up making a small bash command that accomplishes that. It furthermore allows one to "cd" to a file, which is very helpful when you want to change your directory to that of a given finder file. Simply write cd, and drag the file to the terminal and your are there.

Add the following to your .bashrc or .alias file

alias cd=mycd

mycd(){ 
  if [ -f "$*" ]
  then
   \cd  "`dirname $*`"
  else 
    \cd "$*";
  fi

  echo "\cd \""`pwd`\""" > ~/.todir  ; 
  PS1='\[\033]0;`pwd | xargs basename`\007\]\e[31m\w:\e[0m
'
}

Finally, you need to change your terminal settings:

In terminal:settings:shell - make the shell complete the following command:

source ~/.todir; clear

Next time you start your terminal - you will automatically be redirected to your last opened directory - the terminal title will change title when you use the cd alias, and your prompt will show the full directory path.

share
add comment

LAME encode .wav to .mp3

This is the original one-liner I used to eventually craft this handy command.

find ./ -name "*.wav" -execdir lame -V 3 -q 0 {} \;
  • Converts 20Mb .wav (at the highest quality settings) to .mp3 in 3 seconds!
  • Simply install the LAME binary and you're golden.
share
add comment

In your ~/.bash_profile

export PS1="\[\e]2;\h - \w\a\e[32;1m\]%\[\e[0m\] "

This puts your machine name and current directory in the terminal title bar, so you can keep track of where you are. This also shows the data in the Window directory.

share
add comment

You can browse and search the history by using the cursor keys after adding

bind '"\e[A": history-search-backward'

bind '"\e[B": history-search-forward'

to your .profile.

share
add comment

As of Mac OS X Lion 10.7, Terminal supports a few "less"-compatible pager commands when there are no processes running in a terminal. This is useful for paging through and reading text after commands have completed/exited. Supported keys are:

space: Page Down
+Space: Page Up
: Scroll down one line
/: Scroll up/down one line
F: Page down ("forward")
B: Page up ("back")
<: Home (scroll to top)
>: End (scroll to end)

Terminal has commands that will lookup and display man pages, which these keys are indispensable for viewing. See the Help menu and contextual menus. It also supports Services for opening man pages from other applications (enable them in
System Preferences > Keyboard > Keyboard Shortcuts > Services).

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

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

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

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

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

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

Add a file named "-i" to your home directory. Now if you accidentally type:

rm -rf *

it will expand to:

rm -rf -i your other files

and you will be prompt to confirm or deny the removal of the entire dir. It's pretty hacky, but it's saved my butt before.

share
1  
just alias rm to rm -i : alias rm='rm -i' –  Slomojo Jan 29 '11 at 9:28
add comment

BBEdit version for viewing man pages:

bbman () {
  MANWIDTH=160 MANPAGER='col -bx' man $@ | bbedit --clean
}
share
add comment

Automatically update the Terminal.app window title to display your username, host and current directory.

If I do the following:

cd ~/Developer

I want the Terminal window title to be updated to:

jason@rocksteady:~/Developer

To achieve this, make sure that the PROMPT_COMMAND variable is set in your ~/.bash_profile:

PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007"'

Of course, you can substitute whatever suits your fancy.

share
show 1 more comment

Set bash to exit a script immediately on any error.

set -o errexit

Always a good idea when developing bash scripts, especially destructive ones.

share
add comment

An easier way to open and close DMGs is:

open <My disk image>.dmg

Then to close it:

umount /Volumes/<My disk image>
share
1  
if you use umount like that, you'll leave the /Volumes/<My disk image> folder lying around. Use diskutil eject /Volumes/<My disk image> instead, it'll clean up after you. –  Slomojo Sep 4 '11 at 23:25
add comment

To connect to a network volume, you could use mkdir;mount and umount;rmdir etc, etc... however that's long-winded and there's a better Mac specific alternative method...

You can open a share:

open afp://user:pass@server/sharepointname

and eject it with:

diskutil eject /Volumes/sharepointname

By the way, you can also open a dialog to select from a list of all the sharepoints on a server by doing..

open afp://user:pass@server/

Omit the user/password to prompt for credentials in the GUI.

share
add comment

user42053 mentions adding a file -i to every folder. Gets a bit hairy seeing -i in every folder everywhere else. Easier method would be

alias rm="rm -i"
share
4  
This is a baaaaad idea since you'll get too used to this, what if you're on a system without it and you do a careless rm -rf? –  Mark Szymanski Aug 3 '11 at 19:34
add comment

List all directories alone in a directory - er - folders in a folder.

ls -la | grep '^d'

Find sizes of given directory - again - er - folder.

du -s dirname
share
add comment

Drag the proxy icon of a Finder window to get an escaped path; especially useful after typing cd

share
show 2 more comments

I made an alias called dirstat, named for a similar utility. It helps determine where all the hard drive space is being used. Add it to your /etc/bashrc or as a bash script.

du -s ./* | sort -n| cut -f 2-|xargs -i du -sh {}
share
add comment

I've added the lines below to my ~/.bash_profile file.

With the you will see the effect by starting a command/path and hitting a few times.

Change function of to scroll through autocomplete options:

bind '"\t":menu-complete'

SSH as root to...:

alias shroot="ssh -l root"

Force eject volumes:

alias forceeject="hdiutil detach -force"

Force quit an application:

alias forcequit="killall -HUP"

Open man pages as PDFs:

pdfman() { man $1 -t | open -f -a Preview; };

Alias pingburst:

alias ping2="ping -c2"
share
show 1 more comment

You can use esc key as replacement for alt. >ou have to tap it first and then enter the other instead of holding it. It's a standard feature, but more important as the key on macs works different as on "windows/Linux" keyboards.

You can set the behavior of alt key in preferences to behave like on "windows" keyboards. Though you then will be unable to type important characters as @, \, {, ...

Very important if you use emacs in terminal. But suppose there are many commands that require it - eg you can also copy-paste in bash with emacs bindings.

share
show 1 more comment

I find it useful to copy text to the clipboard from Terminal.app without using the mouse to make a selection.

This seems to only works with the older Terminal.app from Tiger. I just renamed it to Tiger Terminal.app, and it still runs fine on Leopard. Haven't tried it on Snow Leopard.

So, with Tiger Terminal, you can do mouse-free copy by typing ++, then using the arrow keys to move to the start of the area you want to copy. Next, type ++ again to anchor the selection point. Use the arrow keys (some emacs-like commands also work for navigation like ctrl+E) to move to the end of the region you want to copy. Finally, type ++ again to copy selection to the clipboard.

share
add comment

One I actually use quite a lot is uptime. Simple but nice :) Currently mine returns up 32 days, 14:30.

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

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

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