Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

Anonymous Subroutines

The Bourne shell allows you to group more than one command together and treat them both as a separate command. In effect, this is creating an anonymous subroutine inline.

For example, if you want to copy a large number of files from one place to another, you could use cp, but this may not be semantically ideal for any number of reasons. Another option is to use tar to create an archive on standard output, then pipe that to a second instance of tar that extracts the archive.

The basic commands needed are show below. The first command in this example archives the listed files and prints the archive contents to standard output. The second command takes an archive form standard output and extracts the files.

tar -cf - file1 file2 file3 ...
tar -xf -

Thus, to copy files from one place to another, you could pipe the first tar command to the second one. However, there’s a problem with that: because the second tar is running in the same directory, you are extracting the files on top of themselves. If you’re lucky, nothing happens at all. In the worst case scenario, you could lose files this way.

Thus, you need run two commands on the right side of the pipe: a cd command to change directories before extracting the archive and the tar command itself. You can do this with an anonymous subroutine.

Here is a simple example:

tar -cf - file1 file2 file3 | \
    { cd "/destination" ; tar -xf - ; }

Notice the semicolon before the close curly brace. This is required. Also notice the space after the opening curly brace. This is also required. Forgetting either of these will cause a syntax error.

Of course, as written, there is still some risk involved in using this code. If the destination directory does not exist, the cd command fails, and the tar command executes in the wrong directory. To solve this problem, you should check the exit status of the first command before running the second one.

For example:

tar -cf - file1 file2 file3 | \
    { if cd "/destination" ; then tar -xf - ; fi; }

This version will execute the cd command, then execute the second tar command only if the cd command was successful.



< Previous PageNext Page > Hide TOC


Last updated: 2008-04-08




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice