Mac Terminal Reference: 40+ Useful OS X Terminal Commands

February 15, 2009 — 65 Comments

Here are a bunch of Mac terminal commands sorted into general categories. I have intentionally omitted long bash scripts and AppleScripts and focussed instead on small useful commands that can be plugged into bigger scripts or used on their own… enjoy!

Terminal & Shell Basics

cmd+n – Open a new Shell in a new window
cmd+t – Open a new Shell in a new tab of the current window
control+d – Logout the Shell in the current tab / window
cmd+d – Split pane. this is not a new shell, just a way of displaying the current Shell.

System

Restart Mac OS X:

sudo shutdown -r now

Shutdown Mac OS X:

sudo shutdown now

Power Management / Energy Saving

Get overview of current Power Management Settings:

pmset -g

Put display to sleep after 15 minutes of inactivity:

sudo pmset displaysleep 15

Put Computer to sleep after 30 minutes of inactivity:

sudo pmset sleep 30

…Also see my post about hibernate mode and Safe Sleep on the Mac

OS X Look and Feel

Permanently disable Dock icon bouncing

If you don’t like the way Mountain Lion now makes the User ‘Library’ folder invisible, you can disable this.

chflags nohidden ~/Library

…you don’t need to relaunch the Finder.

Disable Dashboard (don’t forget to drag the Dashboard Dock icon off the Dock too):

defaults write com.apple.dashboard mcx-disabled -boolean YES
killall Dock

Enable Dashboard:

defaults write com.apple.dashboard mcx-disabled -boolean NO
killall Dock

Force the Finder to show hidden files (very useful for Web Developers who need to edit .htaccess files, for example):

defaults write com.apple.finder AppleShowAllFiles TRUE

Force the Finder to hide hidden files (ie: back to the default setting):

defaults write com.apple.finder AppleShowAllFiles FALSE

Networking

Ping a host to see whether it’s available:

ping -o leftcolumn.net

Troubleshoot routing problems to a host using traceroute:

traceroute leftcolumn.net

Check whether a host is running an HTTP server (ie: check that a Web Site is available):

curl -I www.leftcolumn.net | head -n 1

Automatically enable Internet Sharing at startup

Manage Windows networks (a drop-in for the NET command on Windows). Too many options to list here, so run this for details:

man net

Use dig to discover Domain information:

dig www.leftcolumn.net A
dig www.leftcolumn.net MX

…and you can also retrieve all available stuff in the DNS Zone for a domain with eg:

dig -t ANY google.co.nz

Who is logged in to your Mac?

w

What’s my user name? This is really useful for bash scripts etc.

whoami

Show routing table:

netstat -r

Show active network connections:

netstat -an

Show network statistics:

netstat -s

Troubleshooting

List all open files (this will take a few seconds to complete on most Macs):

lsof

Restart Bonjour – handy when a Mac ‘disappears’ from the Network:

sudo launchctl unload /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
sudo launchctl load /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist

Eject a CD… it’s never happened to me but you can eject a stuck cd with the following. Note that it won’t always be ‘disk1′:

diskutil eject disk1

Text Manipulation terminal commands

Sometimes you need to take some text from the clipboard or a file, transform it somehow and then use it. Here are a bunch of mac terminal commands that do text manipulation. I’ve assumed you want to transform text from the clipboard and back again; see the notes at the end of the article for info on how to write to and from files instead.

Count number of lines in the text in the Clipboard:

pbpaste | wc -l

Count number of words in the text in the Clipboard:

pbpaste | wc -w

Sort lines of text in the Clipboard and copy them back to the Clipboard:

pbpaste | sort | pbcopy

Reverse each line of text in the Clipboard (ie: make each line appear backwards) and copy them back to the Clipboard:

pbpaste | rev | pbcopy

Strip duplicate lines from lines of text in the Clipboard and copy only one instance of each duplicate line back to the Clipboard (output is sorted):

pbpaste | sort | uniq | pbcopy

Find duplicate lines from lines of text in the Clipboard and copy only one instance of each duplicate line (stripping non-duplicates) back to the Clipboard (output is sorted):

pbpaste | sort | uniq -d | pbcopy

Strip duplicate lines from lines of text in the Clipboard and copy only one instance of each line (stripping duplicates entirely) back to the Clipboard (output is sorted):

pbpaste | sort | uniq -u | pbcopy

Tidy up HTML in the Clipboard and copy it back to the Clipboard:

pbpaste | tidy | pbcopy

Display the first 5 lines from the Clipboard:

pbpaste | head -n 5

Display the last 5 lines from the Clipboard:

pbpaste | tail -n 5

Convert tabs to spaces for the lines in the Clipboard:

pbpaste | expand | pbcopy

Other useful commands

Password protect your web site! Create a CRYPTed user/password for using in a .htpasswd file. Save the outputted results of A below to a file called .htpasswd in the directory you want to secure. Then save the contents of B to a file called .htaccess in the same folder.

A:

htpasswd -nb username password

B:

AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/your/site/.htpasswd
require valid-user

Display a history of commands used in the terminal by the current user:

history

Convert a file to HTML. Support formats are Text, .RTF, .DOC.

textutil -convert html file.extension

Nano is a very easy-to-use text editor for quick changes to text files. It is less powerful than VIM but has the advantage of clearly showing you the common editing commands:

nano [file_to_edit]

…In nano, use ctrl+o to Save and ctrl+x to quit.

Greg shared a way of tidying the terminal window. Essentially this command scrolls down a page, clearing the current view:

clear

iTunes

Change iTunes link behaviour to point at local iTunes Library instead of iTunes Store:

defaults write com.apple.iTunes invertStoreLinks -bool YES

Change iTunes link behaviour to point at iTunes Store instead of local iTunes Library (ie: back to the default):

defaults write com.apple.iTunes invertStoreLinks -bool NO

Other Mac OS X Terminal Resources

Mac OS X Hacking Tools (old but detailed list for the obsessive only).

Cameron Hayne’s Bash Scripts

Mac OS X Hints

Apple Forums

Note: For commands where I’ve used pbcopy to get the contents of the Clipboard as input, you can use the contents of a file as input instead. Swap pbpaste for:

cat [/path/to/filename]

And to put the results into a file on your desktop, just swap | pbcopy for:

> ~/Desktop/filename.txt

 

mac terminal command, applescript primer

Hey if you find this page useful, check out my new Mac Terminal Commands ebook. It contains all the commands here, plus many new ones, and other useful stuff to do with the OS X Terminal, bash, AppleScript, and Automator. Get started with Mac scripting tools now. More Info >

 

 

By Jay Docherty

Posts

65 responses to Mac Terminal Reference: 40+ Useful OS X Terminal Commands

  1. Great resource – thank you! I’m used to looking up a command but I can never remember the syntax etc a month or so later. So bookmarking this will be very useful. Lots of things in your list I hadn’t heard of, too – will be fun to experiment with these.

  2. Minor correction:
    Your code to enable Dashboard is the same as the disable code.
    Should be:
    defaults write com.apple.dashboard mcx-disabled -boolean NO
    killall Dock

  3. Thanks JS, fixed that typo.

  4. Some of these (In fact… MOST of these.) aren’t Mac exclusive.

  5. Thanks for your comment… Good point, I was really focussed on Mac OS X because there are obviously many Linux/Unix resources on the Web already. Off the top of my head, the ‘defaults’ command will not work, nor will ‘pmset’. Also, there are no ‘pbcopy’ or ‘pbpaste’ commands, at least not on Debian.

  6. Awesome! The less than .05% of Mac users that will find this useful thank you!

  7. Awesome! The less than .05% of Mac users that will find this useful thank you!

  8. when i’m nano’ing as I’ve come to call it, i can’t seem to paste new strings in like i could in any text editor. i’m using terminal. is there any reason why my pastes are going to the top of the terminal every time, regardless of where i highlight or paste in the terminal?

  9. You need to make sure you use the keyboard to navigate in the terminal. If you click with the mouse it does not set the cursor where you click, so you’ll paste at the default place, somewhere at the top. Use the arrow keys to navigate around.

    Here’s the man page, worth a look:

    http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/nano.1.html

  10. “Clear cmdwin” is a good one if your terminal window is full and you want it to Helios you just opened it, it scrolls down 6 or 12 lines and gives you a “fresh command window again essentially.

  11. Thanks Greg, I’ve added it to the list.

  12. It’s me again, I made a mistake, it’s just clear, not clear cmdwin.

  13. You’re right… anything following ‘clear’ is ignored. Cheers!

  14. Re: using clear function
    You can achieve same result via [cmd]-[k], although not in single-user mode (only supports clear).

    Note: this can become a compulsion, so careful.

  15. Nice, that’s handy. Note that cmd+k actually clears all the scrollback lines, whereas clear actually just pushes them out of the current view. Cheers!

  16. Is there a terminal command that will set the label-color of a folder to blue?

  17. This should work:
    osascript -e "tell application \"Finder\" to set label index of item (\"~/Desktop/foo.txt\") to 5"

    …but Adobe Photoshop CS3 seems to have installed some bad script extension son my mac so osascript is broken for me right now. You’ll need to play with the number, it should be 4 or 5 I think. Good Luck and let us know how you get on…

    trying that script again:

    osascript -e “tell application \”Finder\” to set label index of item (\”~/Desktop/foo.txt\”) to 5″

  18. Kerrie Poliness March 14, 2011 at 7:00 pm

    How can I turn off web sharing in the system preferences on a 10.3 via single user mode. What do I type? The system 9 has unmoutable errors and I suspect system 10 wont start up because I was silly enough to turn it on to see if that would fix something else. System wont start up it stalls on the last few start up things.

  19. Hmm, well I have actually never used single-user mode, sorry, but if you can get terminal access then from the terminal you can get the pid of Apache with ‘top’ (look for ‘httpd’), then ‘kill -9 [pid].’ There may be several processes for httpd depending on your configuration.

    Hope that helps…

  20. I’m having some issues with the one to password protect a folder. Granted, I’m brand new to using terminal so i’m probably making a really obvious mistake that people will laugh at me for, but what does it mean that your instructions have the commands on separate lines? Are they to be entered individually, or just in a string on one line? I tried the latter but it said ‘-bash: AuthType: command not found’

  21. You need to run command in A in the terminal on your mac, and select and copy the line of text it returns. This is a username/password combo, which you paste into a new file named ‘.htpasswd’ in the folder you want to protect. The contents of B are not typed in the terminal, they are pasted into another text file named ‘.htaccess’ – make sure you update the ‘AuthUserFile’ line to reflect the actual location of the .htpasswd file you created above. Usually its something like /home/example.com/public_html/.htpasswd.

    Note that this is a command for protecting folders on apache web servers, not on your Mac. I suspect you might actually be after a tip to do the latter? If so, just select the folder you want to control in the finder, hit cmd I, and then under ‘Sharing & Permissions’ make sure your own login has ‘Read and Write’ access then set everyone else to ‘No Access.’

    You can also protect a folder by making an encrypted disk image, which seems to work well. Instructions here: http://support.apple.com/kb/ht1578

  22. How to disable sleep mode permanently command?

    Please suggest.

  23. Depends. To disable sleep in any condition:
    pmset -a sleep 0

    To disable sleep only when AC power (charger) is present:
    pmset -c sleep 0

    …you will probably need to ‘sudo’ these.
    …Also just note that I got this info from the pmset man page on my Mac. It should work as documented, but I haven’t tested it. Finally, I would urge caution when disabling sleep in the absence of AC power.

    Have fun with your new MacBook Server (or whatever)!

  24. is there a command to disable ssid broadcast when making your own adhoc network….yes yes i know it doesnt make it more secure i just really want to know because we are not allowed to use wifi in afghanistan and i want to share my macs ethernet internet to my ipad but i dont want them to know im doing this….and no they do not have sniffing software.

  25. If you’re using an airport device with the Airport Utility, it’s easy (Wireless Options -> Create a Closed Network), but if you’re talking about internet sharing then sorry, the best information I can find is this, which seems to indicate that it can’t be done. I’d pick up a cheap airport device and use that… good luck in any case…

  26. How to i enable “Adobe QT 32 Server” on my Firewall?

  27. Sorry for the late approval, I’ve been away from my mac.

    If you’re using little snitch or something similar, see this:
    http://kb2.adobe.com/cps/857/cpsid_85711.html

    …If not, then your mac won’t be firewalled. People have reported problems with this software. If you have freezing issues you should try upgrading all codecs and plugins first. Good Luck!

  28. thanks! great scripts
    very useful for me

  29. How to view deleted internet history with Terminal?

  30. Hmm, that’s an interesting one. I’d suggest trying to attempt recovery of Cache.db. Instructions are here:

    http://www.chriswrites.com/2011/06/undelete-files-using-terminal-in-mac-os-x/

    …the specific file you want to recover is this: /Users/[yourNameHere]/Library/Caches/com.apple.Safari/Cache.db

    …and then parsing Cache.db somehow. There are some suggestions here: http://hints.macworld.com/article.php?story=20031021123427554

    If the cache isn’t there you can try: cd .Trash followed by a simple ls. That would show recently trashed & emptied items. There are also commercial tools for this stuff. And Computer Security experts, for a price!

  31. Newbie here. Just ran a traceroute w no problems.
    But. How do I “get out” of that and return to “home”
    quit, exit, etc. go unanswered.
    TIA,
    A

  32. Hold down ‘Command’ (next to the space bar on the keyboard and press the ‘Q’ key. This works for almost any Mac app. Cheers!

  33. Hey Joe:
    Thanks for your reply. However, I don’t want to quit the Terminal, I just want to quit/stop the traceroute “action”. It keeps adding asterisks. I tried entering exit and quit but got no response within the Terminal app.

  34. Hey Avik,

    Hold down ‘Control’ and hit ‘C’.

    Cheers!

  35. Great info, thanks

  36. Wow, you’re taking on all comers… how about this one:

    How can I dump extended file info (the textual equivalent of command-i from the finder) within a terminal? I don’t mean the single line that the ‘file’ command gives…. I want everything command-i shows.

  37. That’s a tricky one. I don’t know, sorry. There are freeware or shareware tools to do this. Try asking on osxhints… cheers!

  38. In my opinion, the best disk eject command is “drutil tray eject” Works even if your computer doesnt have a try, but it does it without the interference of Disk Utility.

  39. @Cameron — try xattr

  40. Hi there.
    Is there a command that would allow me to shutdown computers on the same internet network? I have a mac and pc and just thought it would be fun! i know you can do it from pc to pc but mac to pc?
    thanks
    M

  41. The easiest way is probably to install some kind of remote shell: there seem to be a few options for SSH services: Cygwin, for example. Then use shutdown.

  42. Posted by Joe “The easiest way is probably to install some kind of remote shell: there seem to be a few options for SSH services: Cygwin, for example. Then use shutdown.”

    Ummmmmmm… im a little confused because I’m new to terminal. could you describe what all this means!
    thanks much
    M

  43. Also when i type in shutdown it says: Not super-user.
    Eeek! i am now totally confused!

  44. Ok, ignore those last comments,
    i have enabled superuser and have my password for it so i type in “su”, put my password in, and then i try to shutdown my pc using this:
    shutdown -s \\My Computers IP -r -c
    but just as everything looks good this pops up: bad time format.
    I’ve tried everything but it still says the same thing.
    So close yet so far away!
    please help
    Thanks
    M

  45. @morgsta: if you’re running that on your mac from the terminal then you need to ssh or somehow get onto your pc shell, otherwise the terminal is trying to run shutdown on your mac, which is quite different. -s is the parameter for shutting down at a particular time. You need to cponnect to your pc first with ssh, then run the pc’s shutdown app.

    Hope that helps. If all else fails: sneakernet!

  46. Mmmmmm… Ive been trying to do shutdown in X11 but i haven’t had an internet connection to try it on. il’l see how i go. Otherwise thanks for your help and yeah sneakernet’s probably the easiest!

  47. For showing hidden files, make sure to run “killall Finder” after the posted command. This relaunches Finder. Alternatively, you can go to the force quit window and select relaunch Finder. Same goes for re-hiding hidden files.

  48. Great site, I write AppleScripts mainly, but I was interested in learning at least a little shell scripting on the side. Appreciate the tips.

    My site is http://www.squidoo.com/applescript

  49. Your first tip (“shutdown – r now”) has 2 problems:
    1: most users will have to use “sudo”
    2: there is a typo: there should be no space between “-” and “r”.
    The correct command should be (leave the quot. marks out when pasting):
    “sudo shutdown -r now”

  50. Thanks pie, I’ve fixed these issues now.

  51. Hi, how to send password after su command automatically in a script without user entry?

  52. Try piping it into sudo -S. Like this :

    echo somePassword | sudo -S nano /etc/hosts

  53. hi
    It’s a good post.Thank you for sharing.

Trackbacks and Pingbacks:

  1. Netzschilder #5 | mac my life - October 27, 2009

    […] Eine Sammlung von 40 nützlichen Shell Skripts und Terminal Befehlen. Feste Klicken […]

  2. A Collection of 250+ Terminal Commands, Hacks, Tips and Tuts for Mac OS X - November 12, 2009

    […] 40 Useful Mac OS X Shell Scripts and Terminal Commands […]

  3. OS X Command Line Utilities | OS X | chipwreck - May 7, 2010

    […] – great resource from Apple (PDF)A-Z list of OSX commandsOSX Daily – lots of tips40 Useful Mac OS X Shell Scripts and Terminal CommandsLeave a Reply… Your Comment Your Name […]

  4. Nifty Terminal History Trick! - May 12, 2010

    […] covered the ‘history’ Terminal command before, but here are two other ways of getting at things you’ve typed […]

  5. OS X Terminal Tutorials - February 9, 2012

    […] leftcolumn.net/2009/02/15/40-useful-mac-os-x-shell-scripts-and-terminal–commands […]

  6. Mas OS X terminal tricks « Constantly Underwhelmed - March 28, 2012

    […] is a good list of some basic but useful terminal commands to know on Mac OS […]

  7. Basic Shell Commands For Bloggers « fbguide.info - April 13, 2012

    […] 40 Useful Mac OS X Shell Scripts and Terminal Commands […]

  8. Recopilatorio de trucos para el terminal de Mac OS X | Factor Noticia - September 29, 2012

    […] 40 Useful Mac OS X Shell Scripts and Terminal Commands […]

  9. windows run commandsPing TTL . - November 4, 2012

    […] For Mac users , a userful post is available on leftcolumn website. […]

  10. Running 'Linux scripts' on Mac or Windows systems | TechRepublic - February 1, 2013

    […] 40 Useful Mac OS X Shell Scripts and Terminal Commands […]

  11. Peter Gyger online | KURS Mac OX X Server - August 7, 2013

    […] http://www.leftcolumn.net/2009/02/15/40-useful-mac-os-x-shell-scripts-and-terminal-commands/ […]

Leave a Reply

*

Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>