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

1 2 3 4

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|improve this answer
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 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|improve this answer
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|improve this answer
10  
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
5  
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
show 2 more comments

If you have XCode installed, running the command purge at the terminal is really helpful. It frees up all of your active and inactive RAM. It's useful for people like me who do a lot of audio production (or any kind of media editing for that matter) when you only have 4 GB RAM. You would be surprised how fast 4 GB gets used up.

share|improve this answer

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

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

A relevant command for Terminal.app on Mac OS X is to launch Software Update from the CLI:

sudo softwareupdate -i -a

The bonus is you do not get any nagging from having to click on windows. I run this as part of a update script that is run every week approximately (so that I do not miss the feedback as it may happen when doing this automatically).

share|improve this answer
show 3 more comments

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

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

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

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

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

Create a new directory and enter it:

md() { mkdir -p "$@" && cd "$@"; }

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

Some useful aliases:

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'"

# Get readable list of network IPs
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" # Flush DNS cache

alias gzip="gzip -9n" # set strongest compression level as ‘default’ for gzip
alias ping="ping -c 5" # ping 5 times ‘by default’
alias ql="qlmanage -p 2>/dev/null" # preview a file using QuickLook

# Upload image to Imgur and return its URL. Get API key at http://imgur.com/register/api_anon
imgur() { curl -F "image=@$1" -F "key=ANONYMOUS_IMGUR_API_KEY" https://api.imgur.com/2/upload | egrep -o "<original>.+?</original>" | egrep -o "http://imgur\.com/[^<]+" | sed "s/imgur.com/i.imgur.com/" | tee >(pbcopy); }

All of these are in my ~/.bash_profile so I can use them in every Terminal window.

P.S.

alias chpwn="chown"

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
show 1 more 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|improve this answer

ctrl-R will allow you to perform a reverse search within your bash shell. It's like an interactive form of history.

share|improve this answer

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|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

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

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

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|improve this answer
show 1 more comment
drutil eject cd

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|improve this answer
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 1 more 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|improve this answer
show 1 more comment
alias ka="killall"

Probably one of my most used commands. I put this in my .bash_profile for easy access.

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 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

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

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
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
 dot_clean .

This one isn't an every day usage - but it was a big time saver once - I had a SMB fileserver (Avid Unity) that was displaying lots of .filename files for mac users as well as PC users.

This cleaning command totally fixed the problem (after running twice)

share|improve this answer
2  
its great to finally know theres a good way to do this. – jkp May 2 '11 at 18:13
1 2 3 4

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.