Tell me more ×
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|improve this question
4  
There is a similar thread on Server Fault as well: serverfault.com/questions/7346/… – Chealion Oct 7 '09 at 23:07
4  
You can use open for everything: URLs, images, documents. I use it everyday. – olt Jul 6 '10 at 14:48
1  
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

118 Answers

afplay ~/path/to/file.mp3

Let's you play songs from the commandline. You can also append [space]& and let it run in the background. :)

share|improve this answer

I often use +K to have my Terminal screen cleared instead of UNIX Command clear.

The difference is clear hides the previous commands from our sight, but we can still scroll back meanwhile +K clears it completely—we can't scroll back.

I like using it because I can always press ctrl+R or type:

history | grep command-that-I-want-to-do-again

if I want to re-type a command without a need to look at "messy character crowded" Terminal.

share|improve this answer
history|awk '{print $2}'|awk 'BEGIN {FS="|"} {print $1}'|sort|uniq -c|sort -r

Gives you a list of some of your most recent commands, numbered by how often you use them.

share|improve this answer

I have the following aliases and functions in ~/.bash_profile:

alias ..="cd .."
alias ...="cd .. ; cd .."
alias ls="ls -G" # list
alias la="ls -Ga" # list all, includes dot files
alias ll="ls -Gl" # long list, excludes dot files
alias lla="ls -Gla" # long list all, includes dot files
alias stfu="osascript -e 'set volume output muted true'"
alias pumpitup="sudo osascript -e 'set volume 10'"
alias ips="ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1'"
alias myip="dig +short myip.opendns.com @resolver1.opendns.com"
alias flush="dscacheutil -flushcache"
alias gzip="gzip -9n"
alias ping="ping -c 5"
alias ql="qlmanage -p 2>/dev/null" # preview a file using QuickLook

# Create a new directory and enter it
md() { mkdir -p "$@" && cd "$@"; }

# Define a term using Google
define() { local y="$@"; curl -sA "Opera" "http://www.google.com/search?q=define:${y// /+}" | grep -Po '(?<=<li>)[^<]+'|nl|perl -MHTML::Entities -pe 'decode_entities($_)' 2>/dev/null; }

# gzip a file with strongest compression settings
ubergzip() { gzip -9n < "$@" > "$@".gz; }

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

# Open a man page in TextMate.app
tman() { MANWIDTH=160 MANPAGER='col -bx' man $@ | mate; }

# Quit an app cleanly
quit() {
    for app in $*; do
        osascript -e 'quit app "'$app'"'
    done
}

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

# Uninstall an app with AppZapper
zap() { open -a AppZapper /Applications/"${1}".app; }

For more, see my dotfiles repository on GitHub, and/or view my .osx file for OS X-specific preferences and settings.

share|improve this answer

Command line shortcuts to toggle visibility of hidden files in finder:

alias show_hidden="defaults write com.apple.finder AppleShowAllFiles TRUE && killall Finder"
alias hide_hidden="defaults write com.apple.finder AppleShowAllFiles FALSE && killall Finder"
share|improve this answer

You can transfer a working directory from one Terminal window to another with these two commands added to your .bash_profile file:

alias cwd='pwd | pbcopy'
alias gowd='cd "`pbpaste`"'

cwd copies your working directory from one window, and gowd opens that directory in another window.

share|improve this answer
show 1 more comment

Here is a script that gets the path(s) to the current selection(s) in Finder:

#!/bin/sh

osascript` << EOT

tell application "Finder"       
        set theFiles to selection
        set theList to ""
        repeat with aFile in theFiles
                set theList to theList & POSIX path of (aFile as alias) & " "
        end repeat
        theList
end tell

EOT

How I use it:

$ cat `selected`
share|improve this answer

Ok, definitely not mac specific, but TAB completion in zsh is so good I think it deserves a specific mention.

You get completion of options, e.g.

find . -d[TAB]

will give you -daystart -delete -depth as possible completions.

Also path completion is improved over Bash completion, for example, I have a Volume called Wubly, and inside that video/tv/comedy, so typing:

cd /v/w/v/t/co[TAB] 

will expand to.

cd /Volumes/Wubly/Video/TV/Comedy

(note that it's also case insensitive.)

If there are multiple paths that match this pattern, they will be shown.

Completion is also interactive, so you can move around the available choices with the cursor controls.

share|improve this answer

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

Cmd-{Left arrow, Right Arrow} 

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

share|improve this answer
show 1 more comment

If you need to open a Finder window as the root user, you can execute the following from the terminal:

In 10.5 and below:

sudo /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder

In 10.6:

sudo /System/Library/CoreServices/Finder.app/Contents/MacOS/Finder

Then, open a new finder window. You'll see that the new finder window opens with root permissions.

share|improve this answer
show 1 more comment

When cding, one of the most useful features is tab completion.

For example, instead of entering cd FooBarBazBax, you can enter cd FooB followed by Tab. Tab completion will work as long as the part of the path or filename you entered isn’t ambiguous.

However, if you were to type cd foob followed by Tab, the completion wouldn’t work, as the folder name starts with an uppercase F. Luckily, you can make tab completion even more useful by making it ignore the filename case.

Add this to your ~/.inputrc file (create the file if you don’t have it already):

# Make Tab autocomplete regardless of filename case
set completion-ignore-case on

This way, cd foob followed by Tab would complete it into cd FooBarBazBax, provided there’s a folder with that name in the current working directory.

share|improve this answer

Just type

purge

and it will make inactive memory as free again. Mac OS X keeps apps in memory for a while after you close them, so they will open fast if you open them again. Purge will remove them from memory and give your free memory back.

share|improve this answer

Simulate to type Command-F, to fullscreen a video from command line. Useful when launching a movie in mPlayer from ssh.

osascript <<END
tell application "System Events" to keystroke "f" using {command down}
END

Of course you can also use this trick to simulate any other "typing".

share|improve this answer
show 1 more comment

what about

cat somefile.txt | say

say the contents of a text file... or...

cat someFile.txt | say -o someAudioFile

take your text file, convert it to .aiff

share|improve this answer
show 1 more comment

As of Mac OS X Lion 10.7, Terminal will open a new window if you drag a folder (or a text pathname) onto the application icon. If you drag to the tab bar of an existing window, it will create a new tab in that window.

You can also do this from the command line or a shell script:

open -a Terminal /some/path/

This is the command-line equivalent of dragging a folder onto the Terminal application icon and will open a new terminal window at "/some/path".

Terminal also now supports Services for opening a terminal at a selected folder (e.g., in Finder) or a text pathname using the contextual menu. You can enable them in

System Preferences > Keyboard > Keyboard Shortcuts > Services

Look for New Terminal at Folder and New Terminal Tab at Folder. You can even assign command keys to them if you like.

Finally, if you drag a folder or pathname onto an existing tab (i.e., the tab in the tab bar) and the foreground process is the shell, it will execute a "cd" command in one step. As in previous versions, dragging a folder onto the terminal display will insert the pathname to the folder.

share|improve this answer
show 1 more comment

You can set the system volume automatically too, and kill the screen process afterwards:

screen
(hit enter)
sleep 300; osascript -e "set Volume 10"; say "I am feeling fabulous"; open "http://www.youtube.com/watch?v=dQw4w9WgXcQ"; killall SCREEN
Ctrl-a-d
(detaches)
share|improve this answer
show 3 more comments

Text file to an Audio file

say -o “audiofile.aiff” -f “textfile.rtf”

more syntax here

share|improve this answer

If you use subversion, opens FileMerge for local checked out files that have been changed.

Requires installation of fmscripts:

cd ~/Downloads && svn co http://soft.vub.ac.be/svn-gen/bdefrain/fmscripts && cd fmscripts
sudo make

alias sfmdiff='svn diff --diff-cmd fmdiff'

Then in a checked out directory:

sfmdiff . 

(or any specific dir or file)

share|improve this answer

Flush the DNS cache if you are editing /etc/hosts a lot to test staging servers as looking like production.

dscacheutil -flushcache
share|improve this answer
show 1 more comment

I include all my favorites here: http://rustyisageek.blogspot.com

Example:

Set Volume to 10 and Say something

sudo osascript -e "set Volume 10" | say "hello World"

Wait for network to be ready in a script

/usr/sbin/networksetup -detectnewhardware
share|improve this answer

In Terminal's Help menu, you can search for man pages. (The first time you do this, it can take a few seconds to index the man page files, so wait a bit for results to appear, but subsequent searches are fast.) It will show man page results in the Help menu search results. Selecting one opens a window displaying the formatted page.

As of Mac OS X Lion 10.7, there are a number of enhancements to man page support:

  • Man page searching lets you supply section numbers/names in various formats: "2 open", "open 2", "open(2)". It also supports asterisk "*" for wildcard searches.
  • It now searches all the files in MANPATH (prior to Lion it only searched a fixed set of directories, so, for example, it didn't find any X11 man pages). It doesn't run in a shell, however, so if you want to customize MANPATH you may need to customize man.conf (x-man-page://1/man), or set it in your global environment.
  • There are commands in the Help menu for opening man pages (Open man Page for Selection) and performing an apropos search (Search in man Pages for Selection). There are corresponding commands in the contextual menu, and there are Services you can enable to perform these lookups from other applications (System Preferences > Keyboard > Keyboard Shortcuts > Services > Open man Page in Terminal / Search man Pages in Terminal).
  • If there is no selected text, Open man Page for Selection will automatically look at the text to the left of the cursor. This means you can enter a command name, then use this command to open the man page before entering command arguments. It'll skip over whitespace. It also understands man page references "open(2)" and URLs "x-man-page://2/open". (If you explicitly select text, it also understands "2 open" and "open 2".)
  • Man page windows use the "Man Page" settings profile. You can customize this to alter the appearance of man pages displayed using these commands. It also remembers the position of man page windows separately from other windows, so you can have man pages appear in the same place on screen each time, independent of where you place other terminal windows.
  • + double-click will open man page references "open(2)", enabling you to navigate references from one man page to another. (+ double-click will also open any recognized URL, or even some patterns like email addresses—creates a new mail message—and domain names—opens in Safari.)
  • When viewing a man page window (or any terminal whose commands have all completed/exited), Terminal supports some "less"-compatible pager commands: space = Page Down, +space = Page Up, F = Page Down ("forward"), B = Page Up ("back"), = Scroll down one line, / = Scroll up/down one line.
share|improve this answer

gzip a file with strongest compression settings:

ubergzip() { gzip -9n < "$@" > "$@".gz; }

For more, see my dotfiles repository on GitHub, and/or view my .osx file for OS X-specific preferences and settings.

share|improve this answer
4  
+1 for the "uber" ;-) – trolle3000 Jul 26 '10 at 20:52

Define a term using Google:

define() { local y="$@"; curl -sA "Opera" "http://www.google.com/search?q=define:${y// /+}" | grep -Po '(?<=<li>)[^<]+'|nl|perl -MHTML::Entities -pe 'decode_entities($_)' 2>/dev/null; }

For more, see my dotfiles repository on GitHub, and/or view my .osx file for OS X-specific preferences and settings.

share|improve this answer

If you’re like me, you have multiple Terminal.app tabs open at the same time.

Now, if you open three tabs at the same point in time, then enter some commands in each of them, then close them all, the Bash shell that Terminal.app uses only remembers the command history for the last tab that you close. So, the command history from the other two tabs gets lost.

If you don’t want to lose your command history in any tab, add this to your ~/.bash_profile (or any other file that gets sourced when a new Terminal tab is opened):

# Append to the Bash history file, rather than overwriting it
shopt -s histappend
share|improve this answer

Mount iDisk from command line:

osascript <<END
tell application "Finder"
mount volume "http://idisk.mac.com/john.doe/" as user name "john.doe" with password "StR0NGP455"
end tell
END
share|improve this answer

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

function take {
    mkdir $1
    cd $1
}
share|improve this answer
6  
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|improve this answer
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|improve this answer

This is not OSX specific (man says it's from 4.0BSD), but I love it anyways:

sudo shutdown -h +45

In the above example, shutdown shuts down your computer in 45 minutes from now (as one might suspect).

It's great for when you want to spend "just a little bit of time" on your computer before going to bed / doing the dishes / going jogging / whatever. But when you also know deep down that it's not going to be "just a little bit of time"...

Cheers!

share|improve this answer
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|improve this answer

protected by Community Aug 29 '12 at 21:39

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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