Skip to content

Mac OS X Command Line Tutorial

fonnesbeck edited this page Sep 7, 2012 · 1 revision

While much of OS X is graphical, much of its power still resides with the command line tools available through the Terminal.

OS X is based on FreeBSD, a UNIX-compliant operating system.

This means many powerful UNIX tools are available to Mac users:

  • Apache
  • network utilities
  • compilers

Over 1000 commands!

OS X File System

The OS X filesystem is a hierarchy, or tree, of folders and files,

At the top is a folder called the root directory.

Below the root directory are system folders that you might recognize:

  • Applications
  • Users
  • Volumes
  • Library
  • System
  • bin
  • usr
  • etc

Each directory contains subdirectories. Subdirectory names are separated by forward slashes (Windows/DOS uses backslashes).

Opening Terminal

Located in /Applications/Utilities.

The Terminal is an application that runs commands.

Opening the terminal presents the following:

Last login: Fri Sep  7 09:28:20 on ttys003
Cepeda:~ fonnescj$ 

This is output from a special program that runs inside the terminal called the shell. The shell does four things:

  • displays a prompt for recieving commands
  • reads your and interprets commands
  • runs commands, locating any necessary programs
  • prints the output of the command, if any

First line is date and time of last login, plus the type of terminal being used.

Second line shows the name of your machine, followed by your user name and a prompt ($).

You can open a new window with cmd-N or a new tab with cmd-T.

The prompt indicates that you can type a command.

Try using echo:

$ echo Hello $LOGNAME!
Hello fonnescj!

Most commands use the following syntax:

$ command -option1 -option2  ... argument1 argument2 ...

Arguments are additional information required for some commands. Options are settings that affect the behavior of the program, and are usually preceded by one or two dashes.

Unlike DOS/Windows, UNIX shells are usually case-sensitive.

Several Useful Commands

cal: displays a calendar

$ cal sep 2012
   September 2012
Su Mo Tu We Th Fr Sa
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

ls: lists contents of a folder

$ ls /Volumes
Backup      Macintosh HD    MobileBackups

If you wanted to list all of the files with a .txt extension, you can use the wildcard symbol (*):

$ ls *txt
oilspill.txt        oilspill_count.txt  values.txt

wc: count the number of lines, words, bytes

$ wc oilspill.txt
       0    1986   25134 oilspill.txt

Let's combine some commands, using the pipe | symbol

$ ls $HOME/Documents | wc -l
      13

df: display free disk space

$ df -h /
Filesystem     Size   Used  Avail Capacity  iused    ifree %iused  Mounted on
/dev/disk0s2  233Gi  144Gi   88Gi    63% 37913533 23155907   62%   /

top: show the processes running on your system

To print a static list of all running processes, use ps:

$ ps ax
  PID   TT  STAT      TIME COMMAND
    1   ??  Ss     2:56.64 /sbin/launchd
   11   ??  Ss     0:08.43 /usr/libexec/UserEventAgent (System)
   12   ??  Ss     0:16.38 /usr/libexec/kextd
   14   ??  Ss     0:27.99 /usr/sbin/notifyd
   15   ??  Ss     0:41.63 /usr/sbin/securityd -i
   16   ??  Ss     0:05.37 /usr/sbin/diskarbitrationd
   17   ??  Ss     5:05.07 /usr/libexec/configd
   ...

uptime: show how long your computer has been running

$ uptime
10:41  up 3 days, 23:48, 5 users, load averages: 1.16 1.00 0.94

This includes current time, uptime, number of users, and load averages for the past 1, 5, 15 min.

ipconfig: view IP configuration

$ ipconfig getifaddr en0
10.43.245.108

This shows the ethernet IP address.

curl: downloads a file from the internet

$ curl -O https://dl.dropbox.com/u/233041/simple.py
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1927  100  1927    0     0   2363      0 --:--:-- --:--:-- --:--:--  4700

mv: moves a file from one location to another

$ mv simple.py ~/Desktop

clear: clears the terminal

open: opens files and directories using their default applications

$ open ~/Documents

sudo: allows commands to be run as another user, usually as an administrator

$ sudo softwareupdate -l
Software Update Tool
Copyright 2002-2010 Apple

Software Update found the following new or updated software:
   * JavaForOSX-1.0
    Java for OS X 2012-005 (1.0), 65288K [recommended]

more: examine the contents of a file

$ more values.txt
27,<2,4,-0.27,-0.13
27,2to4,5,-0.35,-0.31
27,5to7,3,-0.46,-0.31
27,8to11,3,-0.27,-0.33
27,12to18,5,-0.57,-0.51

locate: find filenames

$ locate .bash
/Users/fonnescj/.bash_history
/Users/fonnescj/.bash_profile
/Users/fonnescj/.bashrc
/Users/fonnescj/dotfiles/.bash_profile
/Users/fonnescj/dotfiles/.bashrc
/usr/local/Cellar/ack/1.96/etc/bash_completion.d/ack.bash_completion.sh
/usr/local/Cellar/git/1.7.11.1/etc/bash_completion.d/git-completion.bash
/usr/local/Cellar/git/1.7.12/etc/bash_completion.d/git-completion.bash
/usr/local/Cellar/git/1.7.9.2/etc/bash_completion.d/git-completion.bash
/usr/local/Cellar/hub/1.10.2/etc/bash_completion.d/hub.bash_completion.sh
/usr/local/etc/bash_completion.d/ack.bash_completion.sh
/usr/local/etc/bash_completion.d/git-completion.bash
/usr/local/etc/bash_completion.d/hub.bash_completion.sh
/usr/local/texlive/2011/texmf-dist/scripts/changes/delcmdchanges.bash
/usr/share/emacs/22.1/etc/emacs.bash
/usr/share/git-core/git-completion.bash

kill: terminate a process

Some of the more commonly used signals:

 1       HUP (hang up)
 2       INT (interrupt)
 3       QUIT (quit)
 6       ABRT (abort)
 9       KILL (non-catchable, non-ignorable kill)
 14      ALRM (alarm clock)
 15      TERM (software termination signal)

Let's kill our browser!

$ ps ax | grep Safari
24748   ??  R      0:04.82 /Applications/Safari.app/Contents/MacOS/Safari -psn_0_18084158
$ kill -9 24748

Navigating the file system

By default, when you open a terminal the shell is located in your home directory. You can always check what the present working directory is by using pwd:

$ pwd
/Users/fonnescj

Notice the leading slash before Users; this shows that this is an absolute path. A relative path (i.e. relative to the working directory) has no forward slash:

$ ls Library
Accounts        Fonts           Preferences
Address Book Plug-Ins   Fonts Disabled      Printers
Application Scripts Frameworks      PubSub
Application Support Google          R
...

This is different than:

$ ls /Library
Application Support Graphics        QuickTime
Audio           Image Capture       Receipts
Automator       Input Methods       Ruby

There are two important shortcuts for relative paths:

  • '.' refers to the current directory
  • '..' refers to the parent directory

Thus,

$ ls ..
Shared      fonnescj

You can move from one directory to another using the cd (change directory) command:

$ cd Library/Application\ Support
$ pwd
/Users/fonnescj/Library/Application Support

If you would rather not type the entire directory name, clicking the tab button will attempt to auto-complete it, as long as you have typed enough letters to uniquely identify a folder.

Clever tricks

Appending filenames

To add an arbitrary appendix to a filename, try:

mv file{, =old}

For example,

$ mv values.txt{,.old}
$ ls val*
values.txt.old

Restart your computer

Shut down or restart your computer by using shutdown (the -r flag restarts).

sudo shutdown -r now

Re-use an argument

Use the !$ argument to repeat the argument from the previous command:

$ ls /usr/local/bin
GraphicsMagick++-config         lconvert
GraphicsMagick-config           lefty
GraphicsMagickWand-config       libpng-config
R                   libpng15-config
Rscript                 list_instances
...

$ cd !$
cd /usr/local/bin

Search your command history

Typing ctrl-r will bring up a search tool that scans your command history for letters that you type:

(reverse-i-search)`c': cd /usr/local/bin

Typing crtl-r again will get the previous instance.

Read a file out loud

say will read files out loud through your computer's speakers. If we send a text file to it, your Mac will read it out loud:

$ cat values.txt | say