Wilson Mar bio photo

Wilson Mar

Hello. Hire me!

Email me Calendar Skype call 310 320-7878

LinkedIn Twitter Gitter Google+ Instagram Youtube

Github Stackoverflow Pinterest

The terminal is your friend, who only speaks a foreign language


This tutorial describes how to make use of Terminal to make your life easier and less frustrating.

What Apple calls the Terminal is a Bash shell.

Open Terminal from Finder Folder

Ways to open a Terminal command line:

  1. Hold down the command key down while pressing tab multiple times until Finder is highlighted in the pop-up list.

Get to the Finder list of files and folders:

  1. Hold the Option key and right-click the Finder icon in the Dock, then select Relaunch.

  2. Press the command key with your right hand and option+esc key combo with your left hand for the Force Quit menu. Then select the Finder and click Relaunch.

  3. Click the Apple button at the upper-left corner to select Log out. Then log back in to your user account.

If you’re a developer, it’s hard to get away from using a command-line terminal. But if you’re using a MacOS just for social media, you won’t need a Terminal. Perhaps that’s why it’s kinda buried:

  1. Click the Finder icon on the bottom.
  2. Click Applications on the left pane.
  3. Click Utilities.
  4. Click Terminal.

    This would place you at your user Home directory.

PROTIP: Since Yosemite, you can open a Terminal to a folder listed within Finder by pointing your mouse on it, then tapping with two fingers on the touchpad/mousepad.


  1. Click the Apple icon, System Preferences....
  2. Press K and select Keyboard.
  3. Click Shortcuts, Services.
  4. Scroll to the Files and Folders section.
  5. Check on New Terminal at Folder.
  6. Close the dialog by clicking the red dot at the upper left corner.

Text Command Line Bash Shortcuts

These come from the bash terminal on Linux machines:

  • control + ` = cycle through session windows
  • control + left = previous session
  • control + right = previous session
  • control + A = Go to Beginning of line (as in A to Z)
  • control + E = Go to End of line
  • control + U = Clean line
  • control + K = Kill line from under the cursor to the end of the line.
  • control + Y = Retrieve line
  • control + N = Next line
  • control + P = Previous line
  • control + H = Backspace left of cursor
  • control + D = Delete right of cursor
  • control + F = Forward cursor
  • control + B = Backward
  • control + R = Record a shortcut between quotes

See https://linuxacademy.com/blog/linux/ten-things-i-wish-i-knew-earlier-about-the-linux-command-line-2/

Terminal File Listing Home Folder

By default, the Terminal shows the hard drive and lowest level file folder name, in white letters over black.

  1. To show the present (current) working directory (folder):


    The response for me is:


    You will of course have a different machine user name than wilsonmar.

  2. Note the pwd command is built internally to the Bash shell:

    type pwd

    The response:

    pwd is a shell builtin

  3. To get back to the home folder:



    cd ~/

    Alternately, use the $OLDPWD environment variable that MacOS automatically maintains to remember the previous working directory so that you can switch back to it:

    cd -

    List files and folders

  4. List all file names (without any metadata):


    Folders available by default include Documents, Downloads, Pictures, Desktop, Music, Movies.

  5. Note the ls command is an external command added to the Bash shell:

    type ls

    The response lists where ls is defined:

    ls is hashed (/bin/ls)

  6. Dive into a folder type:

    cd mu
  7. Press Enter.

    Nothing happens because upper case letters are important.

  8. Press delete to remove the mu and type:

    cd Mu
  9. Press Enter for the Music folder.

  10. Go back up a level:

    cd ..
  11. List all files with their permission settings:

    ls -ls

    Notice that no hidden files are listed.

  12. List all hidden files with permission settings, piping the listing to more instead of having results flying by:

    ls -la ~/ | more

    A colon appears at the bottom if there is more to show.

  13. Cancel the listing, press control + C.

    Notice the .bashrc on the first page, something like:

    -rw-r--r--  1 discworld discworld  3330 Mar 10 16:03 .bashrc

    (It’s for the Bash Shell.)

  14. If it’s not listed, create it with:

    vi ~/.bashrc
  15. To make it rw r r:

    chmod 644 .bashrc 
  16. List only hidden files in the current folder:

    ls -ld .??*
  17. Create a Projects folder to hold projects downloaded from Github:

    mkdir Projects

    This only needs to be done once.

Show Hidden Invisible Files in Finder

By default, the Mac’s Finder does not show hidden files.

  1. Close all Finder folders.

  2. Enter this in Terminal before typing Return:

    defaults write com.apple.finder AppleShowAllFiles TRUE && killall Finder

    This causes all Finder windows to be reset.

    To make invisible files visible again:

    defaults write com.apple.finder AppleShowAllFiles FALSE && killall Finder

    A description of each keyword:

    defaults - OSX’s command to change defaults, apple’s low-level preference system.

    write - tells defaults you want to change a preference, or write it

    com.apple.finder - defaults that the application’s preferences you want to change is Finder, specified by the application’s bundle identifier.

    AppleShowAllFiles - specifies which preference you want to change within the application.

    TRUE or FALSE - the value you want to set the preference to. In this case, it is a boolean, so the values must be TRUE or FALSE. I think you might be able to use YES or NO, but I’m not sure.

    && - a terminal operator to run whatever’s after this if the previous command is successful.

    killall - kills processes or closes applications.

    Finder - specifies the process or application to close.

For more on this, see http://www.westwind.com/reference/OS-X/invisibles.html

Cursor to Screen Hot Corners

By default, if you move the mouse to one of the corners of the screen, stuff happens. It can be annoying.

  1. Click the Apple menu at the upper left corner.
  2. Select System Preferences.
  3. Select Desktop & Screen Saver.
  4. Click Hot Corners at the lower-right corner.

PROTIP: Disable each by selecting the dash (last choice) so they show up when not wanted.

Cat, tac, tail

  1. Show text file contents to the Terminal console:

    cat /etc/hosts

    BLAH: The Linux tac command to list backward is not in Mac:

    tac /etc/hosts
  2. Show a file in -reverse (bottom-up):

    tail -r -n2 /etc/hosts

    Change n2 to a different number of lines to show.

    PROTIP: This command is useful to see the lastest entries appended to the end of a large log file.

  3. Expose spaces at end of lines by showing $ end-of-line characters that are otherwise not shown:

    cat -vet /etc/hosts

Terminal Ping Host

Find the IP address of a website host name:

host microsoft.com
microsoft.com has address
microsoft.com has address
microsoft.com mail is handled by 10 microsoft-com.mail.protection.outlook.com.

Hosts file

Mac, Windows, and Linux systems have a hosts file that locally does the work of the public DNS – translating host names (typed on browser address field) to IP address numbers.

  1. Edit the hosts file on a Mac:

    atom /etc/hosts

    The default contents: localhost broadcasthost
    ::1 localhost
    fe80::1%lo0 localhost

    fe80::1 is like for IPV4, but actually IP address 169.254.. in IPV4, an address not often used.

    fe80:: is a block of IPV6 addresses reserved for link-local addresses used for packets sent only to directly connected devices (not routed). The network discovery protocol (NDP), which replaces ARP and DHCP in IPv4, is the biggest user of link-local addresses (NDP sorta .

    Each IPV6 interface has a different link-local address starting with fe80:: and (typically) ending with a modified version the interface’s MAC address (EUI-64 format) to ensure a unique address on a segment.

    Programs such as OpenVPN add to the bottom of the file:

    # BEGIN section for OpenVPN Client SSL sites  client.openvpn.net
    # END section for OpenVPN Client SSL sites
  2. Flush the cache:

    dscacheutil -flushcache

DNS Configuration with NameBench

Analysis at one time showed this ranking by speed:

  1. UltraDNS at
  2. Google at,
  3. OpenDNS at,,

Google Namebench tries the speed of various DNS servers from YOUR machine (which takes some time) and pops up in your browser this:

  1. If you don't see the Apple icon at the top of the screen, move the cursor to the very top of the screen for a few seconds.
  2. Click on the Apple icon at the upper left corner.
  3. Select System Preferences.
  4. Click Network.
  5. Click Advanced.
  6. Click DNS.
  7. Click [+], copy, and paste

An example:


Flush the DNS cache since OSX 10.9 :

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

Previously, OSX 10.7 and 10.8, only the killall was needed.

Previous to that, OSX 10.5 and 10.6, only the decacheutil was needed, without the sudo.

BTW, the equivalent for Ubuntu is sudo service network-manager restart while other Linux flavors uses sudo /etc/init.d/nscd restart. Windows uses ipconfig /flushdns.

Clear DNS Cache Cache

Different commands are needed for different versions of OS. OSX 10.10 added requirement for sudo when using the built-in discoveryutil:

sudo discoveryutil udnsflushcaches

OSX 10.9

dscacheutil -flushcache;
sudo killall -HUP mDNSResponder

OSX 10.7 to 10.8

sudo killall -HUP mDNSResponder

OSX 10.5 to 10.6

sudo dscacheutil -flushcache

Windows by contrast:

ipconfig /flushdns

Linux (depending on the flavor running)

/etc/init.d/named restart
/etc/init.d/nscd restart

Create Terminal Aliases

Most developers leave files un-hidden. But if you want to just type showFiles and hideFiles to show and hide Mac OS X’s hidden files, consider this article to create such terminal aliases.

An example is an alias for the tree command by adding this in the ~/.bash_profile script:

   alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"


Brew install tree

OSX does not come with the tree command that many other Linux distributions provide. So add it using brew:

brew install tree
Active Terminal sessions need to be closed so new Terminal Shell New Window Shell has this activated.

See list of parameters:

tree \-\-help

List only 2 levels deep with human-readable file size kilobytes and sort by last modified date:

tree -L 2 -s -h -p -D -t

Bash Profile Configuration

The profile file is run during boot-up to configure the terminal to define file path, shims, and autocompletion handlers.

This is the single biggest frustration with people using Linux on Mac.

One of the earliest articles on bash at http://www.macdevcenter.com/pub/a/mac/2004/02/24/bash.html shows shell variables, environment variables, and aliases.

Each operating system has its own file name for its profile:

  • With Ubuntu: Modify ~/.profile instead of ~/.bash_profile.
  • With Zsh: Modify ~/.zshrc file instead of ~/.bash_profile.
  • With Fish: Modify `~/.conf/fish/config.sh` to append.

If there is both a .bash_profile and a .profile file, boot-up only executes the first one it finds.

On my Yosemite Mac, open a terminal and:

cd ~

View the file using the vi editor that comes with OSX:

vi .bash_profile

According to the bash man page, .bash_profile is executed during login before the command prompt, while .bashrc is executed for interactive non-login shells such as when you start a new bash instance by typing /bin/bash in a terminal.

Here’s what my profile file begins:

echo ".profile"
export NVM_DIR="/Users/wilsonmar/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm
export PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

Exit vi by typing :q

Some installers request that adding a $PATH using a command such as:

echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile

To execute profile with the changes:

source  ~/.bash_profile

Alternately, to install GHC copy and paste into ~/.bash_profile:

# Add GHC 7.8.4 to the PATH, via http://ghcformacosx.github.io/
export GHC_DOT_APP="/Users/wilsonmar/Applications/ghc-7.8.4.app"
if [ -d "$GHC_DOT_APP" ]; then
export PATH="${HOME}/.cabal/bin:${GHC_DOT_APP}/Contents/bin:${PATH}"


To run a bash script while avoiding the confirmation prompt:

set -- -f; source bootstrap.sh

Terminal Usage

This page contains notes for system administrators and developers, who need to control Macs below the UI level, which require typing commands into a command-line terminal screen.

To list open files (process id’s and ports, actually):

sudo lsof -i -P

To avoid text wrapping, pull the right edge to expand the screen width.

The right-most column heading "Name" shows the port (either TCP or UDP).

To filter a particular port number:

sudo lsof -i -P | grep 8080

The second column, PID, lists the process identifier. Copy a number for use in the kill command:

sudo kill 289

Operating System Kernel

I can use Linux commands in my version of the operating system:

uname -a (a for all) or uname -rvm


14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64

which is a combination of:

uname -r for release number,
uname -v for kernel version,
uname -m for model:

x86_64 for Intel or AMD 64-bit or
i*86 for 32-bit.

For more information about Darwin operating system developed at Apple, see:

  • http://www.wikiwand.com/en/XNU and
  • https://www.wikiwand.com/en/Comparison_of_operating_system_kernels

NOTE: lsb_release -a which works on Debian, RHEL 6.6, and Ubuntu is not recognized on Gentoo nor CentOS 6, which has no folder /etc/lsb-release.

Distriwatch.com describes releases.

Setup Your Mac Like a Pro

Paul Irish is one of top pros among developers, and now a Google Evangelist. He put his Mac configuration settings on github.com/paulirish/dotfiles. But he recommends cloning github.com/mathiasbynens/dotfiles/.

On the Git page notice that he has established an industry convention of using Projects folder we defined earlier.

On the Git page I clicked on Clone in Desktop.

The library is called dotfiles because that’s what hidden files are called, and most configuration files are hidden.

Edit terminal prompt setting

Paul Irish offers his setup-a-new-machine.sh at https://github.com/paulirish/dotfiles ZShell (included with Mac and can be set as the default in Terminal) * oh-my-zsh as a ZShell framework * The oh-my-zsh Git plugin * And the oh-my-zsh theme called jnrowe </p>

By default, if you have a long file name, it would leave little room to type in commands before it wraps to the next line.

To redefine what appears in the prompt, edit this file using the vi editor that comes with each Mac: vi .bashrc Copy this and paste to the bottom of the .bashrc file:

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White

bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White

unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White

bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White

txtrst='\e[0m'    # Text Reset

print_before_the_prompt () {
printf "\n $txtred%s: $bldgrn%s \n$txtrst" "$USER" "$PWD"

The command above uses global parameters $USER and $PWD, plus colors from this list.

Exit from the Terminal shell: exit

Environment Variables

Like on PCs, the PATH environment variable stores where the operating system should look to find a particular program to execute.

A big reason to use a command-line terminal is to set environment variables.

To see what is already defined:


http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x talks about setting launchd.conf and rebooting. This applies to all users.

To see what was already defined:

echo $PATH

$PATH must be upper case.

The response I’m getting is:


Root user for sudo commands

The root user has the ability to relocate or remove required system files and to introduce new files in locations that are protected from other users.

Any user with an administrator account can become the root user or reset the root password. A root user has the ability to access other users’ files.

Under a Unix system like Mac OS X you must have “root” (administrative) privileges to start IP-services using ports smaller than 1024.

After Mac install, the root or superuser account is not enabled. While it is possible to enable the root account, once enabled, if forgetten, you’ll have to reboot from the installer drive (a hassle).

It is safer and easier to use the sudo command to gain temporary root access to the system.

DOTHIS: In a Terminal window invoke:

sudo -s After I type in my password, the response for me is the version of bash:


to demote out of root:


DO THIS: The folders that bash looks into are:

/bin/echo $PATH

On a fresh Yosemite, its:


Each additional app adds to the front of the list:


Separating the folders between colon separator:

  • /Library/Frameworks/Python.framework/Versions/3.4/bin
  • /opt/local/bin
  • /opt/local/sbin
  • /Applications/MAMP/bin/php5/bin
  • /Applications/MAMP/Library/bin
  • /Applications/Adobe AIR SDK/bin
  • /usr/local/bin
  • /usr/bin
  • /bin
  • /usr/sbin
  • /sbin

New folders are added to the front of the PATH using a command such as:

export PATH=&LT;new folders>:$PATH

Depending on how you’re setup, file ~/.profile or ~/.bash_profile or ~/.bash_login contains the path echo’d.

Or your PATH may be set in /etc/profile for all users

Clear the terminal history:


Create Windows-like shortcuts with parameters using text editor


Mac OSX doesn’t allow you to create shortcuts like Windows. OSX alias don’t allow parameters (ex. create a Screen Sharing shortcut that connects to a specific computer).

Jessie suggests this to create a Windows like shortcut with parameters in the Comments field.

Another alternative is to use a text editor to create URL shortcut files like the ones Windows Internet Explorer stores its bookmarks. Apple Safari recognizes them when clicked within Finder. So they are cross-platform.

  1. Copy the URL to the clipboard by pressing Command+C.
  2. From within a text editor, open a new text file.
  3. Type at the top of the file: [InternetShortcut]
  4. Paste from clipboard by pressing Command+V
  5. Press enter/return to add a blank line under the URL line.
  6. Save the file with a .url file extension.
  7. From within Finder, click on the file to see it display by Safari.

Mount .dmg files using hdiutil tool

.dmg (Disk Image) files can be mounted from the command line:

hdiutil attach /path/to/diskimage.dmg

The response is like:

/dev/disk1 Apple_partition_scheme
/dev/disk1s1 Apple_partition_map
/dev/disk1s2 Apple_HFS /Volumes/Mounted Disk Image

Note the disk from the message above to unmount (detatch):

hdiutil detach /dev/disk1s2

The same utility can mount .iso images:

hdiutil mount sample.iso

Folders accessed by developers

DOTHIS: In Finder, select from the left panel the first item under the Devices list.

Click on Macintosh HD.

  • Applications hold apps installed.
  • Incompatible Software hold apps which cannot be installed, such as Amazon Kindle, which competes with Apple's iBooks. This occured during upgrade to Yosemite.
  • Library/Library holds Apple internal apps.
  • System hold apps installed.
  • Users hold data for each user defined, as well as a Shared folder accessible by all users.

DOTHIS: Click on your username (wilsonmar in my case). This action is the same as clicking on the last default item under the Favorites list.

Many WordPress developers prefer to add a folder named Sites which holds the wordpress folder expanded from download.

IPv6 compatibility with Curl command line apps

curl http://localhost:3000

When invoked on Mac OS 10.10 (Yosemite), you need to add a parameter to make the request using IPv4:

curl http://localhost:3000 –ipv4

Otherwise, you will see an error message such as:

curl: (7) Failed to connect to localhost port 3000: Connection refused

even if the URL loads fine in a browser.

This occurs because curl, being under Yosemite, uses IPv6 by default but some apps, such as LoopBack.io, by default uses IP v4.

See if you see IP v6 entries in your hosts file (::1 localhost, fe80::1%lo0 localhost). If they are there it is likely that curl is making requests using IP v6.

You can make your LoopBack app use IPv6 by specifying an IPv6 address as shown below:

app.start = function() {
// start the web server
return app.listen(3000, '::1',function() {
console.log('Web server listening at: %s', app.get('url'));

Ulimit Too Many Files

By default, operating systems limit how many file descriptors to allow. Each operating system version has a different approach.

Linux operating systems have this command:

ulimit -a

On my Sierra the response is:

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 256
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 709
virtual memory          (kbytes, -v) unlimited

Check how many file descriptors you have:

launchctl limit maxfiles

On Sierra the response is:

   maxfiles    10240          10240    

The first number is the “soft” number, the second one is the “hard” number.

Such numbers were set with a command such as:

sudo launchctl limit maxfiles 10240 10240

The maximum setting is 12288?

NOTE: To change maxfiles on Sierra, define a plist. TODO: verify

Due to security, OSX Lion removed the “unlimited” option and now requires a number to be specified.

sudo launchctl limit maxfiles unlimited

Disable System Integrity Protection

Some programs make calls to the operating system which OSX began to see as a threat, beginning with El Capitan.

Apple says System Integrity Protection blocks code injection (and many other things).

But what about useful programs (such as XtraFinder) which works by injecting its code into Finder and other application processes?

  • For example, OpenVPN issues a JSONDialog Error “DynamicClientBase: JSONDialog: Error running jsondialog”.

To get around this, you need to partially disable System Integrity Protection in OS X El Capitan. See Apple’s article on how:

  1. Run a full backup to an external USB drive.
  2. Shut down all apps, then the operating system (from the Apple icon).
  3. Reboot the Mac.

    This is needed because System Integrity Protection settings are stored in NVRAM on each individual Mac. So it can only be modified from the recovery environment running in NVRAM.

  4. Boot OS X into Recovery Mode: hold down the command + R keys simultaneously after you hear the startup chime.
  5. When the OS X Utilities screen appears, pull down the Utilities menu at the top of the screen.

  6. Choose Terminal.
  7. Type the following command into the terminal before hitting the return key.

    csrutil disable; reboot
  8. For XtraFinder:

    csrutil enable \-\-without debug
  9. To revert SIP to original state:

    csrutil clear

Skill Certification

Video course Mac OS X Support: Installation and Configure is the first of courses on Plurasight toward Apple Certified Support Professional (ACSP)

Dotfile Settings from others

  • https://github.com/afranken/dotfiles
  • https://github.com/mathiasbynens/dotfiles

Daemons and Agents

  • https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html


To kill all apps and shutdown a Mac right wasy (with no warning and no dialog):

sudo shutdown -h now


  • https://www.hamsterpad.com/chat/typescriptpdx Typescript Slack group

More on OSX

This is one of a series on Mac OSX: