404
votes

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.

14
  • 5
    There is a similar thread on Server Fault as well: serverfault.com/questions/7346/…
    – Chealion
    Oct 7, 2009 at 23:07
  • 5
    You can use open for everything: URLs, images, documents. I use it everyday.
    – olt
    Jul 6, 2010 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, 2010 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".
    – Michael H.
    Jul 12, 2010 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, 2010 at 4:40

133 Answers 133

1
vote

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

function take {
    mkdir $1
    cd $1
}
2
  • 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, 2010 at 18:02
  • You can also "cd !!:1" where !! is the previous command and :1 takes its (zero-based) argument number. Lets say you do "mv file1 file2" and realize you wanted the opposite: "mv !!:2 !!:1". Of course this is only useful for complex names.
    – Eric Darchis
    Aug 9, 2010 at 16:29
1
vote

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
1
  • you don't need xargs for these, mate will accept STDIN.
    – ocodo
    Jan 29, 2011 at 9:29
1
vote

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.

1
1
vote

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.

1
vote

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.
1
vote

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.

1
vote

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.

1
vote

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

1
vote

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.

1
vote

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.

1
vote

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. ;)

1
  • Command-Drag will issue the entire cd command without any typing.
    – Chris Page
    Jan 19, 2014 at 1:37
1
vote

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 -
}
1
vote

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

1
vote

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
}
1
0
votes

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.

1
  • 1
    just alias rm to rm -i : alias rm='rm -i'
    – ocodo
    Jan 29, 2011 at 9:28
0
votes

BBEdit version for viewing man pages:

bbman () {
  MANWIDTH=160 MANPAGER='col -bx' man $@ | bbedit --clean
}
0
votes

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.

1
  • As of Mac OS X Lion 10.7, Terminal supports setting the window and tab (icon) titles separately. "0" sets them both. Use "1" to set the tab title, "2" to set the window title.
    – Chris Page
    Aug 19, 2011 at 11:46
0
votes

Set bash to exit a script immediately on any error.

set -o errexit

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

0
votes

An easier way to open and close DMGs is:

open <My disk image>.dmg

Then to close it:

umount /Volumes/<My disk image>
1
  • 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.
    – ocodo
    Sep 4, 2011 at 23:25
0
votes

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.

0
votes

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"
1
  • 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? Aug 3, 2011 at 19:34
0
votes

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

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

2
  • or drag it and do C-a cd RETURN
    – ocodo
    Sep 4, 2011 at 23:19
  • On Mac OS X Lion 10.7 and later, you can drag a folder (or a proxy icon, or a pathname selected in text) onto the Terminal application icon to create a new terminal window at that location. There are also “New Terminal at Folder” and “New Terminal Tab at Folder" Services you can enable (in System Preferences), which will show up in the contextual menu when selecting folders or pathnames. You can also drag onto an existing terminal tab to automatically issue a cd command, and you can drag onto the blank area of the tab bar to create a new tab at that folder.
    – Chris Page
    Jan 14, 2012 at 22:38
0
votes

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 {}
0
votes

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"
1
  • -1 Please just format commands using the 4 space indent.
    – ocodo
    Sep 4, 2011 at 23:23
0
votes

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.

1
  • A couple points of clarification: The name of the modifier key is “Option”. (It also has “alt” printed on the key to indicate that when you’re using the keyboard with Windows it will perform the same function as “Alt”.) Option is only needed to type characters like “{“ and “}” on certain physical keyboard layouts, e.g., French. It is not used in US English keyboard layouts, for example.
    – Chris Page
    Jan 14, 2012 at 22:46
0
votes

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.

0
votes

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

0
votes
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.

3
  • 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, 2011 at 19:40
  • @bmike Very true.
    – daviesgeek
    Nov 4, 2011 at 21:01
  • I've used drutil eject before to eject a disk from the SuperDrive I removed from my MacBook Pro and placed in an external enclosure. Sometimes the OS doesn't recognize that the enclosure is connected and doesn't respond to the eject button making this command very useful! Jun 15, 2013 at 22:01
0
votes

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .