Skip to content

Terminal Quickie: trash

21-Sep-08

I have been keeping myself quite busy with some other projects, but fear not, the Learning the Terminal series is not dead. Hopefully this will hold you over until I have some time to generate some real content.

Last time, we talked about Terminal and Finder integration. One topic we did not touch upon is how to move files to the Trash from the shell. Perhaps surprisingly, Mac OS does not have a built-in command for trashing files. Sure you can just mv files to the Trash folder directly, but this will not handle name collisions or alternate volumes correctly.

There have been a few attempts at a shell script to mimic the trash behavior, but the best I’ve come across is Dave Dribin’s osx-trash. This version is actually a small ruby program that uses the 10.5 scripting bridge to actually execute the Trash operation through Finder. It works “The Right Way”.

Please see Dave Dribin’s setup and installation directions for more information.

Learning the Terminal on the Mac - Part 4 - Bringing Finder and Terminal Together

09-Aug-08

The first few articles laid out a good foundation of basic shell usage, but little Mac-specific information. In this article, all that will change. We’re going to show a few ways to get back and forth between Terminal and Finder.

From Finder to Terminal

There a few methods to get information from Finder into the Terminal, or use Finder in Terminal-like ways.

Path Bar

One new feature in the 10.5 Finder is Path Bar. The Path Bar makes it easy to see the full path to the current folder. To enable the Path Bar (if you haven’t already), activate Finder, and choose View → Show Path Bar from the menu.

lt2-show-path-bar.png

Once enabled, the Path Bar will appear at the bottom of all your Finder windows, just above the Status Bar. Below is how the Path Bar appears when I have my Home folder open in Finder.

lt2-path-bar.png

The the above path would be interpreted as /Users/demo in the shell.

lt4-ls-path-bar.png

Go to Folder…

Finder also has a built in command called Go to Folder… that allows a path to be entered in a similar way as in the shell. This feature can be accessed by choosing Go → Go to Folder… from the menu, but it’s faster to use the shortcut ⌘⇧G.

lt2-go-to-folder.png

The path entry field of the Go to Folder… feature also has rudimentary tab-completion support. If you type a few letters and either press the tab key (⇥) or just wait a few seconds, it will complete the current path component with the first match it finds. It’s not nearly as good as the completion in bash, but it’s there.

Drag & Drop Paths

Files or folders in Finder can also be dragged and dropped directly onto Terminal. Doing so will insert the path to the file or folder into the shell.

lt4-drag-drop-path1.png

And voilà, the path is inserted into the shell:

lt4-drag-drop-path2.png

OpenTerminalHere

OpenTerminalHere is a small Applescript application that launches Terminal and automatically cd’s to the current folder in Finder. It was originally written by Marc Liyanage and has since been updated to make it more Leopard-friendly. I find it extremely handy, and if you think you would too, go here for the download and setup instructions.

OpenTerminalHere is meant to be installed into Finder’s toolbar. This is done by simply dragging the OpenTerminalHere icon to Finder’s toolbar and pausing a few seconds until a small green “plus” indicator appears next to the mouse pointer. If you want to tweak the position of OpenTerminalHere or add spacing, choose View → Customize Toolbar… in Finder’s menu after installing.

lt4-install-openterminalhere.png

Now just click on the OpenTerminalHere icon in the Finder window’s toolbar, and a Terminal will launch and cd to the current folder.

From Terminal to Finder

Even though the shell is a powerful tool, sometimes you may want to switch back to Finder to finish a task. Here are a couple tools to do just that.

open

We’ve used the open command (man page) a few times already to open files with their default application and folders in Finder. This command is actually specific to Mac OS and is not found in other Unix-like operating systems. The open command also allows you to choose the application with which to open the file, or open the file in the default text editor.

To open a file using a specific application, use the -a option:


open -a [application] [file]

For example, if I wanted to open a file called “hello.txt” in MacVim instead of the default editor, TextEdit, I would type:


open -a /Applications/MacVim.app hello.txt

Also as we mentioned just sentences ago, you can use the open command to open a file using the default text editor. This is done with the -t option.


open -t [file]

Let’s say I’m a curious individual, and I want to see exactly what iTunes stores in its XML library file. I would type:


open -t ~/Music/iTunes/iTunes\ Music\ Library.xml

(Remember those extra \’s are to escape the spaces, which was discussed in the second article.

Revealing Files in Finder

The open command can be used to open folders in Finder, but we don’t have a way to reveal a file within a folder. Many applications have a built-in “Show in Finder” feature, but unfortunately the shell does not. However, all hope is not lost.

One of the simplest ways to add new commands in the shell is through creating shell scripts. Shell scripting is a deep topic in itself, but for know, just think of a shell script as a small program that is interpreted by the shell itself. Shell scripts are written in plain text so they are quick to create and easy to modify.

A hint entitled “Select files in Finder from Terminal” on Mac OS X Hints presents a way add a “Show in Finder” feature to the shell using a custom shell script. Several others submitted improvements and alternative approaches in the comments. The solution I liked best is described in this comment by caesurae.

I liked this solution because it was relatively concise and easy to read (for the bash-literate), and it is contained within a single file. I modified the script very slightly to fix a problem with revealing directories.

Here is the full script. Immediately following is a download link, which is probably more useful. Following that, and even more useful still are installation instructions.

The Script

#!/bin/bash
#
# revealInFinder.bash
#
# 05.26.2006
#
# caesurae@gmail.com
#
# tested on Mac OS X 10.3.9 build 7W98 - Darwin 7.9.0 - AppleScript 1.9.3
#
# reveal the given file(s) and/or folder(s) in a Finder window
#
# usage: revealInFinder.bash ~/dir/file "/dir/dir/my file" file
#
########
#
# 08.07.2008
#
# Andy Mroczkowski
#
# minor update to allow for more reliable opening of directories
#
# tested on Mac OS X 10.5.4 - AppleScript 2.0.1k
#
##

# if no arguments are given, echo the usage string
if [ $# -lt 1 ]; then
  echo 'Usage: '`basename "$0"`' [files]' >&2
  exit 1
fi

# define $n, gets +1 for each argument given
# not sure if $n is needed, how to get index number of $1, $2, etc.?
n=0

# define $act, gets +1 for each argument that passes test
act=0

# step thru each argument one at a time
for thearg in "$@"; do

  n=$(( n + 1 )) 

  # if $thearg exists then
  if [ -e "$thearg" ]; then

    # get the absolute path to the argument
    thearg="`cd \`dirname \"$thearg\"\`; pwd`/`basename \"$thearg\"`"

    # create a applescript statement using $thearg for osascript to execute
    osatext='tell application "Finder" to reveal POSIX file "'"$thearg"'"'
    /usr/bin/osascript -e "$osatext"

    # $act activates Finder after processing the remaining arguments
    act=$(( act + 1 )) 

  # else if $thearg does not exist then
  else

    # if $thearg is not the last argument given then
    if [ $n -lt $# ]; then

      # ask to continue processing the remaining arguments
      echo -n '"'"$thearg"'" does not exist and will be ignored. continue?  (y/n)? ' >&2
      read ans
      case $ans in
        "n" ) exit 1 ;;
        "y" ) continue ;;
      esac

    # else if $thearg is the last arguement then
    else

      # print the "does not exist" string and exit
      echo '"'"$thearg"'" does not exist.' >&2

      # exit status 1 indicates an error occurred
      exit 1
    fi
  fi
done

# if $act is greater than 0 then activate the finder
if [ $act -gt 0 ]; then
  /usr/bin/osascript -e 'tell application "Finder" to activate'
fi

# exit status 0 indicates all is ok
exit 0

Download the reveal script (and unzip it if necessary).

Installation

Once you have reveal downloaded, you need to put it a place where the shell can find it. Executable files are usually kept in a directory called “bin“. To avoid any permissions problems, we’re just going to set up this script for the current user. To create a bin directory for yourself, type:


mkdir ~/bin

Now the reveal script must be moved into the bin directory. If you saved reveal in your Downlaods folder, you would type the following:


mv ~/Downloads/reveal ~/bin

Of course if you saved reveal to some place other than your Downloads folder, you’ll have use the appropriate path.

Finally we need to ensure that reveal is executable. If you downloaded it from the using the link above, the permissions should have been preserved within the zip file, but we’ll reset them just in case. Changing basic permissions from the command line is done with chmod (man page). We’ll go into detail on chmod later. For now just type


chmod +x ~/bin/reveal

Ok, now everything is in place, but there is still one more thing left to do. The shell only looks in a few pre-defined places for programs and although a ~/bin directory is common, it does not search that directory by default. We can tell the shell to look for programs in our ~/bin directory by adding it to our PATH.

The PATH variable controls where the shell looks for programs. You can manually type in the command to add ~/bin to our PATH, but the PATH variable is cleared every time we open a new shell. That’s a hassle. Instead we want it so our PATH is set up for us automatically. To do that, we will add the command to a special file called .bash_profile which is loaded every time a new shell is started.

First, create the file. The file must be in your home directory (~) or the shell won’t find it. If you already have a .bash_profile the following command won’t overwrite it.


touch ~/.bash_profile

Now open the new, empty .bash_profile file in your default text editor:


open -t ~/.bash_profile

Next add the following line exactly as it appears below. Copy and Paste are your friends. If you already have some stuff in your .bash_profile just add it to the end.


export PATH=$PATH:$HOME/bin

Save and close the file. Then close the Terminal you were working in and open a new one (your .bash_profile is only read when the shell starts up).

Congratulations, you now have installed a shell script. Have a beer.

Usage

Our new reveal script is easy to use. You just type reveal followed by one or more paths to files or directories. In fact, if you type reveal with no arguments, it prints a helpful usage statement:


Usage: /Users/demo/bin/reveal ~/dir/file "/dir/dir/my file" file

Of course since we went through all the trouble of putting reveal into our path, we can just type:


reveal ~/dir/file "/dir/dir/my file" file

Here it is in action:

lt4-reveal-in-action.png

Wrap-up

So there we have it - Terminal and Finder peacefully co-existing. What a wonderful world. If you have more suggestions about integrating these fine pieces of software, or a question, feel free to comment. Feedback is always welcome.

I got it goin’ on

17-Jul-08

And what does “it” refer to in this case? Well, several things:

First I’m heading off Paris and Ghent in a couple hours. I most certainly won’t be blogging, and probably not much twittering either. If anything I might update my Facebook status or throw something on my zany new tumblog.

Of course this means no new Terminal article next week. I’ve been trying to get one out weekly (more or less), but the vacation and the inevitable post-vacation catch up will push #4 back a bit. And speaking of the blog and articles…

I’m well aware that the design and layout here is, well, sucktoast. I’ve been trying to actually generate some content before trying to make it all perty (sic). However, I assure you that an improved design that will address a lot of the current layout and formatting issues is being worked on by the (in)famous 20OG design team, and an update should be coming… soon.

Learning the Terminal on the Mac - Part 3 - Basic File Operations

17-Jul-08

By now you hopefully have a good understanding about how to reference files with paths and list files using ls, and move around with cd. Now we’re going to go over basic file operations including:

  • Create
  • Copy
  • Move
  • Delete

There is a lot of information to cover this time around, but I want to make one quick note about the notation being used before we begin. Like the man pages, we’ll use an underline to denote a placeholder for an option or argument to a command to describe its general form. For example, the general way to describe how to change to a directory is:

cd path

Here path is just a placeholder. You would replace it with a path to an actual directory.

Creating Files and Directories

There are actually many, many ways to create files on your Mac using commands in the shell, but I’m going to demonstrate a few quick ways so you can easily experiment with copy, move, and delete operations.

touch

The touch (man page) is a simple command that “touches” a file, meaning it updates its last modification date to the current time.

touch file

A nifty feature of touch is that it will create the file it it doesn’t exist. This command is the easiest way to create a new file to play with. For example to create a file called “Bananas!”:

touch Bananas!

And the same command, in the terminal:

lt3-touch.png

echo

The simplest way to create a file that has some contents is with the echo (man page) command, and output redirection. We’ll cover output redirection in detail soon. For now just follow the form:

echo "some text" > filename

An example:

lt3-echo.png

We snuck in another command there too: cat (man page). cat is used for concatenating (hence its name) files, though it’s most often used for dumping the contents of a text file to the screen.

mkdir

Finally, directories can be created with mkdir (man page).

mkdir new directory

To make a directory called “Stuff” in my home directory:

mkdir ~/Stuff

A simple example, creating the same “Stuff” directory, but using a relative path:

lt3-mkdir1.png

Copying: cp

Copying files is done with the cp command (man page). This command takes at least two arguments; the first being the source and the second being the destination.

cp source destination

Copying a file from my Downloads folder to my Desktop looks like this:


computer:~ demo$ cd Downloads/

computer:~ demo$ cp file.dmg ~/Desktop/

A real example:

lt2-cp1.png

The cp command can also be used to copy several files to a single destination:

cp source 1 source 2 source n destination

For example:


computer:~ demo$ cd Downloads/

computer:Downloads demo$ cp file1.dmg file2.dmg ../Desktop/

Moving: mv

The mv command (man page) command is used for moving files to a different location, or renaming files. It’s usage is very similar to cp:

mv source destination

mv source 1 source 2 source n destination

For example:


computer:~ demo$ cd Downloads/

computer:Downloads demo$ mv file1.dmg file2.dmg ~/.Trash/

Here is a real example of moving a file from my Downloads folder to my Desktop, and then renaming that file:

lt2-mv1.png

Also, mv can be used for moving entire directories. Here’s an example that shows moving a folder called “Stuff” from the Desktop to the home directory:

lt2-mv3.png

Deleting: rm

Files and directories can be deleted (or removed) with the rm command (man page). A word of caution: rm will remove files immediately, skipping the Trash Can. Use it carefully.

rm file 1 file 2 file n

The following is an example using touch to create several files and rm to delete them:

lt3-rm1.png

Recursion

For more information see recursion.

Ok, we got that lame computer science joke out of the way. Recursion isn’t all fun and games, though. It is an option that is found in many shell commands, including some of the ones we just learned! In this context, recursion basically means to include all files including sub-directories, sub-sub-directories, etc. Both cp and rm can be instructed to act recursively with the -r option.

cp -r

With the -r option, cp can be used to copy a directory and all its contents to another location.

cp -r source dir destination

For example, if I wanted to copy my “Documents” folder to a “Backup” volume:

cp -r Documents /Volumes/Backup/

Note that there is no trailing / after the source directory, Documents. This is an important subtlety when using cp -r. If the trailing / is omitted, the directory and all its contents will be copied. However, if the trailing / is included, only the contents of the directory will be copied to the destination, not the directory itself. Here are two examples showing the differences between the two commands:

With a trailing /, only the contents will be copied:

lt3-cp-r2-annotated.png

And now without the trailing /, the entire directory will be copied:

lt3-cp-r3-annotated.png

rm -r

If you thought rm was dangerous before, you ain’t seen nuttin’ yet. Just like with cp, the -r option allows you to remove a directory and all its contents. It is typically paired with the force option, -f, which swallows certain errors and skips all prompts and warnings.

rm -rf stuff you never want to see again

Example:

lt3-rm-rf.png

Be especially careful with -f. There is no undo.

Wildcards

If you haven’t guessed already, bash supports basic wildcards for matching files and paths. The real term for this functionality is globbing, which we’ll cover in more detail in the future. For now, we’ll cover two special characters which you’re probably already familiar with from other pieces of software: * and ?.

Match many characters:*

The asterisk (*), or sometimes called “star”, is the standard “match everything” wildcard. For example, say you want to copy all DMGs from the Downloads directory to /Volumes/Backup, but not the other files.


computer:~ demo$ cd Downloads/

computer:Downloads demo$ cp *.dmg /Volumes/Backup

This would match any file (or directory) that ends with .dmg. However, some DMGs are also zipped and end with .gz or .zip. We can make sure we get all the DMGs but using two asterisks:


computer:Downloads demo$ cp *.dmg* /Volumes/Backup

Most commands that take a path as an argument, including mv and rm will also work with *. But again, be very careful with rm and *.

Here is how you could clean out your ~/Library/Caches folder by moving al its contents to the Trash. If you actually do this, you should reboot after the operation is complete.

lt3-mv-caches-to-trash.png

Match one character: ?

The ? wildcard isn’t used as often as * but it is still fairly common. It differs from * in that it only matches one character. It’s similar to the blank tile in Scrabble. If you many digital photos downloaded from your camera, and they all have names like IMG_0020.jpg and IMG_0164.jpg, you could move them all like this:


computer:New Photos demo$ mv IMG_????.jpg ~/Pictures

The ? only matches a single character, so to match a four-digit number, we need to place four ?’s in a row.

Files and Directories Revisited

You may have noticed that the same commands can be used to copy, move, and delete files and directories (though not create, sorry).

This is because UNIX-based operating systems treat directories as a special kind of file. This means that many of the commands used for manipulating files can also be used for manipulating directories. UNIX actually goes beyond just directories. It also handles things like devices and network sockets as files as well, but that is a bit beyond the scope of our current article.

Wrap-up

The information covered in these last three tutorials should give you a very powerful toolbox. You can now do many of the basic file management tasks you would normally do in the Finder in the shell instead. This article didn’t discuss much Mac-specific information, but the tentative topic for the next article is how to bring the Finder and the Terminal together.

As always, I appreciate your feedback about the current material and future directions. What would you like to see next?

Learning the Terminal on the Mac - Part 2 - The Shell and Paths

08-Jul-08

In the first article we learned how to launch Terminal and get started using the shell. Also we covered some basic commands for moving around, including cd, pwd and ls.

In this action-packed episode, we are going to take a closer look at directories and paths. Usually. I would try to cover material in a bit more breadth before going into depth on a particular topic. However, an understanding of paths is important foundational knowledge, and will be very useful for our next topic, basic file manipulation.

Before diving into paths and directories, I want to share a little more background information about the shell, and also some tips on how to get yourself out of trouble.

About the Shell

This “shell” thing we have been talking about is actually a kind of program. There are several different shells available on the Mac, but the most popular and the default is called bash. Bash stands for “Bourne-again Shell”, was created over 20 years ago and it is still being actively developed[1].

Due to it’s long history in the UNIX world, bash sometimes isn’t the most user-friendly piece of software. Sometimes you can make a typo that puts your shell into a state you don’t understand. Fortunately, all hope is not lost.

Getting out of Trouble

You’re probably familiar with some of the common Mac OS X keyboard shortcuts, such as ⌘S (Save), ⌘P (Print), and ⌘Q (Quit). Most keyboard shortcuts in the graphical part of Mac OS X use the ⌘ (Command key) modifier. These shortcuts are also used in Terminal.app for quitting, closing windows, etc.

However, remember that Terminal.app loads a shell, bash, inside of it. Bash uses a completely different set of keyboard shortcuts, which use the Control key. This key is usually labeled “ctrl” on your Mac keyboard, and uses ^ as its symbolic representation.

If you know only one control sequence in the shell, than it should be ^C. Without going into too much detail, this keystroke is similar to “cancel” or “escape”. If you end up in some mode or program that you don’t understand, you can often get back to the prompt with just ^C.

Perhaps it is best explained with a haiku:

Lost or stuck in bash?

Prompt gone, output out of hand?

^C saves you

Then again, maybe not. Time to move on to our Feature Presentation: Directories and Paths.

Directories

As a Mac user you should already be familiar with using folders in the Finder. Well, a directory is just the more shell-oriented term for a folder, and since we’re working in the shell, we’ll talk in terms of directories most often.

Special Directories

There are a few “special” directories that we should touch on before going further.

The top-level directory in your Mac’s hard drive is referred to as / or the root directory in shell terms. All other directories are descendants of the root directory. It’s easy to navigate to / and see what is there, using cd and ls.

lt2-ls-root.png

The next special directories we need to mention are . (dot) and .. (dot dot). The directory . is just an alias for your current directory. If you type cd . at the prompt, essentially nothing will happen. The purpose of the . directory might not be immediately apparent, but will be because especially useful when we discuss file manipulation.

The .. directory is similar to ., except that it refers to the directory “above” your current directory, also known as the parent directory. Typing cd .. from your home directory will move you up to the /Users directory, and typing it again will put you in / (the root).

These directories will actually be shown in the output of ls if the -a option is specified:

lt2-dot-and-dotdot.png

Astute readers may be wondering about the effects of cd .. if your current directory is /. Well, fear not. You will not accidently change into some forbidden directory, whose contents, once seen, may not be unseen. When in root, cd .. essentially does nothing.

The final magic directory is ~. This is simply a shortcut to your home directory. Every user has one and only one home directory. On Mac OS X, all users’ home directories are in /Users directory. Also you may notice that your prompt shows ~ when you are in your home directory, rather than the full name of the directory (for basic prompt description, see the last article).

lt2-tilde.png

There is one important stipulation when using ~. It does not work inside either single (') or double (") quotes. This is due to the way ~ is implemented in the shell. All the other special directories mentioned in this section have no problems with quotes, however. Look to the escaping and examples sections for how to deal with ~ in paths.

To review:

  • /

    • The top-level directory of your computer’s hard disk.
    • Usually called root or slash.
  • .

    • The current directory.
    • Usually called dot.
  • ..

    • The directory that contains the current, or parent directory.
    • Usually called dot dot.
  • ~

    • Your home directory.
    • Usually called tilde.
    • Won’t work inside quotes!

Paths

We’ve already worked with paths a little bit in the last article with the cd command. Now we will talk about them in a little more detail.

The path separator on Mac OS X is / (called a slash or sometimes forward slash).

Kinds of Paths

There are two kinds of paths, relative and absolute. Relative paths reference files from your current directory, while absolute paths specify the complete location of a file or directory.

This is I how would change to the Downloads directory of my “demo” account using an absolute path.

cd /Users/demo/Downloads

And this is how I would change to the Downloads directory of my “demo” if I was already in my home directory (~).

cd Downloads

Both these commands get me to the same directory, we just got there by a different path.

lt2-ls-downloads-abs-1.png
lt2-ls-downloads-rel2.png

Above, we worked with paths to directories. Well, paths to files work the same way. I could open a file called “Notes.txt” on my Desktop using the absolute path:

open /Users/demo/Desktop/Notes.txt

or a relative path (shown from my home directory):

open Desktop/Notes.txt

Escaping

The shell gives special meaning to certain characters in order to implement all its features. If you are familiar with web programming, this is similar to how URLs are percent-ecoded.

The most notable of these characters is probably the space. The shell uses spaces to separate commands from options and arguments. However, this is a problem if the argument you want already has a space in it. This occurs in many files and folders on Mac OS X, like the “About Stacks.pdf” file we used in the last article.

Special characters are escaped using the \ or backslash character. This can be confusing since this character is used as the path separator on Microsoft Windows. It’s probably best if you can just wipe Windows from your mind entirely (zing!).

To escape a space in a file or directory, with prefix it with a \, like so:

open Documents/About\ Stacks.pdf

Alternatively, you can quote the entire argument, using double quotes ("):

open "Documents/About Stacks.pdf"

Finally, we don’t need to escape the entire path, just the part that actually needs the escaping:

open Documents/"About Stacks.pdf"

Actually, single quotes (') can be used instead, but they have a slightly different meaning. We’ll discuss the meanings of the different types of quotes soon.

Also, note that if you use tab completion the shell will be smart enough to do most of the escaping for you. If you’re hungry for more, you can read more about escaping in the Escaping topic in the Advanced Bash-Scripting Guide.

Path Examples

Here are a few examples of how to put all this knowledge together:

cd .. Go to the directory one level above
cd ../.. Go to the directory two levels above
cd ../../ Go to the directory two levels above (same as previous, extra /’s are ignored)
cd ~ Go to your home directory
cd ~/Documents Go to your Documents directory
cd ~/.. Go to the directory one level above your home directory (Users)
cd ~/Library/Application\ Support Go to your Application Support folder using escaping
cd ~/Library/"Application Support" Go to your Application Support folder using quotes (don’t quote the ~)
open ~/Documents Open your Documents folder in Finder
open . Open the current directory in Finder (see, the . is useful)

Wrap Up

We now have enough knowledge regarding paths to provide a solid foundation going forward. Next up, we’ll be talking about copying, moving, and deleting files. If you have questions, comments, or suggestions for future articles, please note the comments section below. I believe it will accommodate your needs.

Learning the Terminal on the Mac - Introduction and Moving Around

30-Jun-08

The is the first of hopefully several short articles describing the basics of using the terminal in Mac OS X. This is aimed at absolute beginners who have never used a command line interface before. The first few installments are likely to be very screenshot heavy, because the command line has a rather steep learning curve. Every little bit helps.

First, a bit of motivation. If you have no interest in learning to use the terminal, then I probably can’t convince you otherwise. However, if you are slightly curious, here are a few reasons why it might be worthwhile (and fun!) to start tinkering with it.

The terminal…

  • can be faster for some tasks.
  • exposes advanced Mac OS features.
  • opens up access to a wealth of open source software.
  • lets you transfer your skills to other Unix-like operating systems.

Now, just a little bit of terminology before we get started.

Terminal.app, often referred to as just the terminal, is a Mac OS application that wraps an interactive command line interface to your computer called the shell. This article and the ones that follow will really be focusing on the shell, and not Terminal.app itself. These same lessons should apply if you are using another terminal application, such as iTerm or the one built in to Coda. Much of the information can also be transferred to other Unix like operating systems, but we will be using some Mac specific commands as well.


Moving Around


If you haven’t already, open Terminal.app. it’s in the Utilities folder inside your Applications folder, or just type “Terminal” into SpotLight. Once it launches, you should see a window like the one below. I have annotated that section called the prompt. This is where we type commands for the shell to interpret. The information in the prompt itself isn’t relevant quite yet so don’t worry about it.

terminal-prompt.jpg

First, let’s determine where we are. Similar to Finder, your shell is always focused on a directory. This is called the current working directory, or just current directory or working directory. There is a command pwd that prints the working directory (hence its name: print working directory). Type pwd at the prompt and press <return>.

tt1_02-pwd.png

My account name is “demo”, so the shell started in my home directory, which is “/Users/demo”.

Now that we know where we are, let’s see what else is here. The command to list the contents of a directory is ls (think “list”). This is also one of the most commonly used commands. Type ls at the prompt and you should see a list of the contents of your home directory. My “demo” account looks like this:

tt1_03-ls.png

For the sake of completeness, this is how my home directory looks in Finder. All the same folders are there.

tt1_04-finder.png

Let’s move into our Documents folder and see what’s there. We will use another extremely common shell command cd to change the current directory.

The cd command takes the directory to change to as an argument. Arguments follow the command and are separated by spaces.

Type cd Documents and press <enter>. Make sure you capitalize Documents. The shell is case-sensitive.

tt1_05-cd.png


You may have noticed that the prompt changed. The default prompt looks fairly cryptic at first, but it’s actually very simple. The first part before the colon is the computer name or hostname. It may seem like this is superfluous information - of course you are on your computer. But as we’ll see in future articles, this will come in handy. The second portion is the name of the current working directory. Next, we have our current user name, which again will be more useful in the future. The final $ is standard in many shell prompts. It denotes that you are a standard user, as opposed to a root or super user, in which case you would see a # instead.

tt1_05a-prompt.jpg

You probably have a lot more than just one file in your Documents folder, so the contents will scroll off window. This is fine for now. We’ll talk about controlling pagination and output flow soon.

So now we can see all the names of the files, but nothing else. Let’s say we want to see more information akin to the list view in Finder. We’re particularly interested in the size of the files.

In addition to arguments, many commands also take options. They are usually prefixed by the - character, but it can vary. I happen to know that ls has an l option that prints out files in long format. Type ls -l.

tt1_07a-lsl.jpg

Now we see several pieces of metadata associated with our files. There is some permissions information, the file size in bytes, the file’s creation date, and finally the filename. File size in bytes isn’t very intuitive to most people. We tend to think about in kilobytes (K), megabytes (M) and gigabytes (G). Fortunately there is another option, h, that makes the output of ls a little more human-readable.

tt1_08-lslh.png

That’s better. So now let’s say we want to open a Document. We can do this from the shell with the open command. Type:

open “About Stacks.pdf”

The quotes are important (we’ll learn why later), and again don’t forget about the case sensitivity. If you don’t have “About Stacks.pdf”, you can pick another file. The file will open up in your default application for that kind of file.

tt1_09-open.png

Let’s go back to our home directory. A quick way to do this is just type cd with no arguments.

tt1_10-lshome.png

By now you now may be a bit curious about other options for the ls command. (If you’re not, just pretend).

The man command lets us view the manual or man page for almost any command. To display the manual for ls just type: man ls

tt1_11-manls1.png

Use the up and down arrow keys to scroll the page, or space to advance a whole page at a time. Browse around for a bit. When you’re done, type q to quit.

Colorized output sounds interesting. Let’s give that a try.

tt1_12-manls2.jpg
tt1_13-lsG.png

Hooray, pretty colors. By default, it will color directories in blue and executable files in green. This is of course is all configurable. See the man page for more information.

Completion


Up to now we’ve working with relatively simple paths and filenames. However, you may already feel that typing out the full names of files seems somewhat onerous. There is a shortcut known as tab completion that greatly improves path entry at the command line. It is actually a fairly simple technique, so don’t let the seemingly long description that follows scare you. Read over the demo scenario, watch the demo movie that shows the steps in action, and then try it out for yourself.

To illustrate how tab completion works, we’ll set up a simple scenario. We want to view all the custom Preference Panes that are installed for all users of the system. However, we’re not exactly sure where they are stored. We’ll use the ls command and tab completion to efficiently explore the file system.

At the prompt type the following, but don’t press <enter>.

ls /

Now press the <tab> key once. Nothing should happen. This is because it needs more information before it can complete the next part of the path for you. To see all the possibilities, press the <tab> key a second time.

You should see a list of all the files and directories in top-level or root directory of your hard disk. The Library folder seems like a likely place for the Preference Panes to live.

You’ve already typed ls /, and you shouldn’t have pressed the <enter> key yet. Type a L but still don’t press <enter>. You should have the following on the prompt:

$ ls /L

Now press the tab key once. Nothing should happen. This is because it needs more information before it can complete the next part of the path for you. To see all the possibilities, press the key a second time.

You should see a list of all the files and directories in top-level or root directory of your hard disk. The Library folder seems like a likely place for the Preference Panes to live.

You’ve already typed ls /, and you shouldn’t have pressed the key yet. Type a L but still don’t press <enter>. You should have the following on the prompt:

$ ls /L

Now press the <tab> key. If you haven’t any other directories in the root of your disk that begin with capital L, the shell should automatically fill in “Library” for you. Magic!

You prompt should now look like this:

$ ls /Library/

Press <tab> twice (still no <enter>) to show the contents of the “/Library” directory.

The “PreferencePanes” directory looks very promising. Let’s see what’s inside.

Type Pref (the first few letters of “PreferencePanes”) and press <tab> to let the shell complete the rest. Again, don’t press <enter> yet. The shell should complete your path so it looks like:

$ ls /Library/Preference

But notice that the path now says “Preference” and we want “PreferencePanes”. The shell could not complete the path fully because it had more than one match for a folder that begins with “Preference”. To see all the possible matches, press the <tab> key.

We know see that it has matched “Preferences” and “PreferencePanes”. We want “PreferencePanes”. In order for the shell to complete it for us, we need to give it the next letter of the path we want. So we type P and press <tab> again.

Now our prompt should look like:

$ ls /Library/PreferencePanes/

This is the path we want. Now, finally, press <enter> to view the contents. I have the Growl and Flip4Mac Preference Panes installed for all users. Yay.

Here is a demo movie of the same process.

That may have seemed like a lot of work, but tab completion is really a huge time saver. Experiment with it whenever you are typing a path. You’ll soon find that it becomes fairly natural and saves a ton of keystrokes.

One final note on tab completion. You may notice that it sometimes puts weird slashes in the filenames. Take our “About Stacks.pdf” file as an example.

tt1_14-space_escape.jpg

The shell is doing what is known as escaping. We’ll touch on this much more in the future, but basically it’s a way to tell the shell what you really mean. In this case, our file, “About Stacks.pdf” has a space in the name. Remember earlier we said that arguments are separated by spaces. In order to tell the shell to treat the name of the file as one, we need to escape the space. This is why we put the name of the file in “” (double quotes) earlier.

Wrap-up

Up to now we’ve gotten a little background about the terminal and the program that runs inside it, the shell. You should now be able to move around with some efficiency, list files, and open them up. There is still a lot more to learn, but this is a solid start. The next article will cover some more common shell commands. In the meantime, feel free to explore, and if you have any comments or suggestions for future articles, please leave a comment!

WWDC Comedown

15-Jun-08

It’s been a full two days since WWDC ended, which I think is enough time for any residual effects of the Reality Distortion Field to subside. I thought I’d share a little bit about my first WWDC experience.

In summary, it was well worth it for me, and I’d go again. I can see how seasoned vets may tire of it eventually, but at this stage in my Cocoa (Touch) development career I felt it was invaluable. It was slightly different than I expected, but in a good ways:

Misconception 1:

The only first-hand account of previous WWDCs that I heard made it sound like it was an all-night turbo-nerd code-a-thon (not that there’s anything wrong with that). Also, every sort of conference I’ve been to in the past has been sorely lacking in the wall-socket department. I didn’t want to be the chump with the dead battery. Actually, I really didn’t want to be the chump with the dead battery.

(Idea Bubble!)

My attack to the potential power problem was three-pronged (subconsciously inspired by the male AC connector, perhaps).

  • Carry a Power Squid. This way, if I found a socket, but all the plugs where taken, I could just attach my Squid, and then more power for everyone! Squid Boy will save us all!
  • Bring a spare battery. I ordered one especially for the trip, and had it delivered to my hotel.
  • The final contingency plan: a second laptop. That’s right I also lugged my I-can’t-believe-it-still-works 12″ PowerBook with me. Its unlikely that both my previous power access strategies would fail, but this also covered the catastrophic failure of my main laptop.

Misconception 2:

I bumped into a Cocoa programming glitterati and asked him what he thought of this WWDC. He said

There are big years, and little years. This is a little year. 

I didn’t agree. It was a little year for the Mac, but it was a huge year overall, thanks to, you guessed it, the iPhone. How often will an entirely new platform be launched? Not too often, I reckon. I guess it still wasn’t big in terms of unveiling new information since we’ve had the iPhone SDK for some months now, but this was the first time all these iPhone developers, new and old, got together.

In fact, I began to envision that in-progress iPhone apps would be everywhere. Developers would be skipping around the halls of Moscone, gleefully sprinkling beta versions and licenses. Although my own iPhone app experience was very limited (though non-zero), I didn’t want to be left out.

So around 11 PM the night before a 7AM flight, I decide that it would be a Good Idea to upgrade my iPhone to the latest development firmware. What could go wrong? Well apparently, enough to keep me up until almost 4 AM. Pro-tip: read instructions.

I was sleep deprived, but I was ready.

Reality

First, the power. There were power strips everywhere. There was one on every table in the lounge. They routed power into the main seating areas, so you could charge up during a session and not pay attention to the speakers. One day, I even found a power outlet in my soup. Just kidding.

Basically, you had to try to run out of juice. And if you did, they had a special battery charging station. The extra battery got zero use, though I did throw down Ole Squiddy once and made a friend in doing so.

Next, the ‘iPhone Apps For All!’ scenario didn’t pan out. Sure I saw a few demos here and there, and spent zero time in the iPhone lab, but in general, it didn’t seem like people were spending much time hocking their wares.

Nor did they seem to be huddled around furiously coding. In fact, most people, myself included, seemed to try to meet people, absorb information, get a few questions answered, and have fun doing it all. I thought it was great. For me, the best part was socializing with the community. I’m pretty new to the Cocoa scene, so it was really nice to meet all the people I’ve been twitter-stalking. Some where even nice enough to follow me back. I would go as far to say that I made a few new, hopefully lasting friends in the past week.

So as I indicated on my WWDC exit survey, the best thing about WWDC was meeting other Mac developers. The second and third were interacting with Apple engineers and the technical sessions.

Talking with the engineers in the labs was extremely valuable (thanks Image Capture team!), and chatting it up during the extra-ciricular activities was just fun. It made me realize that although Apple’s engineers are definitely smart, but they’re not arrogant, unapproachable, coding geniuses. In fact, they were extremely friendly, and basically, humans just like me. Stunning.

The technical sessions were good, but not great. I got what I expected for most of them, which is way better than I’ve done at any one sort of conference. Also, I was very impressed by the baseline public-speaking and presentation skills of the engineers. I don’t know if Apple just hires good communicators, or trains them, or what, but the quality of end result was high.

Oh, and the sleeper hit of WWDC 2008? The super-nice staff. They gave the whole experience a very pleasant, friendly feel. Bravo, you black-shirted army. Bravo.

WWDC also inspired me to kick it up a bit. Though its against my policy to comment on future blog postings, I can say that I hope more will be coming “soon”. And one more thing…

Save me a spot in line July 11th :)

What I’ve been up to…

17-Apr-08

The frustrating thing about most projects I’ve worked on in the past is that they’re so technical or specialized or intangible that I can’t even describe to friends and family what I’ve been spending all my time on.  Not so this time around.  If you want to see what I’ve been working on (and you have a Mac), you can: 

PRE-ORDER: NEAT Receipts for Mac Advance Release  

Congratulations to everyone on the NEAT Receipts Mac team. 

Welcome to the #1 ranked Andy Mroczkowski site

17-Feb-08

One upside to having a name that contains consonant combinations previously thought to be impossible, is that is easy to get to the top of the Google search results.

FastMac MacBook Pro Battery

16-Feb-08

My original MacBook Pro battery went from providing a reasonable 2 hours of use to less than 10 minutes practically overnight. Also, this happened only weeks after the one-year warranty on my battery expired. Attempts to finagle a replacement battery failed.

Once bitten, I wasn’t all that thrilled about forking over $129 to Apple to replace something that I felt was defective in the first place. But what choice did I have? My search for alternatives only turned up one. Fortunately, that option was a good one.

I’ve been running on a FastMac TruePower MacBook Pro Battery for a month now, and everything is happy so far. FastMac’s battery features:

  • (allegedly) more capacity
  • $30 less price
  • same integrated charge indicators
  • almost identical appearance to the original

There is one feature that they don’t mention, at least not explicitly. The FastMac battery is two ounces lighter than the stock Apple battery. Two ounces might not sound like much, but I noticed it almost immediately. Also, I challenge you to come up with another, non-destructive way to shave weight off a MacBook Pro. Actually, I will revise that. Destructive ways are fine as long as:

  • its not my laptop
  • you post pics

I waited a month before sharing my experiences, because if I didn’t my experiences would have been “Uh, it works”. To gather some actual quantitative data, I’ve been using coconutBattery (which is a cool, and free).

 

Picture 1.png

Not bad, Battery. Keep up the good work.