Advanced Unix Topics


Unix is a highly configurable environment with a wealth of tools. In this section, we introduce some tools and commands available to you when interacting with a shell in Terminal.

Environment and shell variables

Every time you log in, open a new Terminal window, or switch shells, the shell checks its initialization files to establish your environment and your shell variables. Each shell handles its initialization files and environment settings somewhat differently. The default shell (bash) is covered in this section.

First, bash reads files that are referred to as shell initialization files. These files set specific behaviors for the shell. There is usually a system-wide shell initialization file located at /etc/profile, this file will be read and used by all users on the system. Generally a user would like to set personal options for their shell. For this reason, the home directory is scanned for the following invisible files: ~/.bash_profile, ~/.bash_login, or ~/.profile. (Remember that by using a period as the first part of a file name, the file will be invisible to an ls command, unless the -a switch is provided.) For introductory purposes, the three files are functionally equivalent. If none of these files are in your home directory and you want to experiment with changing local variables such as your shell prompt, default editor, and so on, you should create a ~/.bash_profile file and make changes in that file.

Note

By convention, environment variables are all uppercase, and shell variables are all lowercase. Thus, the environment variable PATH and the shell variable path can (and usually do) have different values.

Enter the env command to see a list of your current environment variables and the set command to see a list of your current shell variables. Examples of both are shown in Figure 24-8.

click to expand
Figure 24-8: The env and set commands display environment and shell variables, respectively.

Changing environment variables

You can change environment variable settings or declare new environment variables for the current session by entering a command of the form: export VARIABLENAME=new_value where VARIABLENAME is the environment variable you want to change or declare and new_value is the value you want to give it. This value persists until you log out or exit the shell in which you’re working.

If you want to make the change apply to future sessions, you need to edit the ~/.bash_ profile file (or the ~/.bash_login or ~/.profile file). You can do this with a shell editor, such as vi or emacs. You can also do so with Mac OS X or Classic text editor, such as TextEdit, BBEdit, or SimpleText. But you first have to make an unhidden copy in the shell (the Open dialogs won’t display hidden files), edit that copy, and make sure to save the result as plain text, and then replace the hidden file with the edited copy. Proceed as follows:

  1. If it is a new variable, add the export command to the .bash_profile file. If it is a change to an existing variable, find the line where that variable is declared and change the line.

  2. Save the file and exit the editor.

  3. Enter the command source .bash_profile if you want the change to take effect.

Note

The default location of .bash_profile is your home directory.

The source command feeds the contents of the file arguments to the shell as input.

Changing shell variables

To define a temporary value to a shell variable, use the following command:

variable_name=value

The value of this variable remains set until you exit from this shell. The value of this variable is not exported to other shells when they are invoked.

To give a lasting value to a shell variable, follow these steps:

  1. Use an editor to open your ~/.bash_profile file and add the following line:

    variable_name=value

  2. Save the file and leave the editor.

  3. Enter the command

    source ~/.bash_profile

Doing so adds the value of the shell variable to your shell’s present environment. When subsequent shells are invoked, they also have this variable set.

Creating aliases

No, these aren’t the same aliases available under Mac OS. Unix aliases are pseudonyms for other Unix commands. To create an alias for use with the bash shell, add the command alias aliasname=what-it-stands-for to the ~/.bash_profile file and enter the source .bash_profile command, making the obvious substitutions.

One example of an alias is the following:

alias what=’ps –aux | grep $USER | more’

This command sequence pipes (sends) the output of the process status command as input to grep, which searches that input for the processes you’re running and then displays the results a screen at a time.

You can even chain multiple commands together in an alias by separating them with semicolons. For example, alias tree ‘cd; ls –R’ would display a complete directory hierarchy of a user’s home directory when the command tree was entered.

Manipulating text file contents

Just as Unix provides you the cat, pr, head, tail, more, and less commands (mentioned earlier in this Chapter) to display files or parts of files, it provides a variety of editors and other tools with which to create, edit, and summarize text file contents. In addition to the ancient command-line editor, ed, you also have vi, pico, and emacs, all of which are screen editors. Screen editors offer functionality between line editors where you entered commands describing the editing action you wanted to take and the direct manipulation windowing editors, such as TextEdit. In a screen editor, file contents are displayed on a terminal screen, and you move the cursor around via the keyboard and shift modes between overstrike and insert, with the option of still using the commands of the old-line editors. Although multiple editors are available in Mac OS X, among the screen editors, only vi is guaranteed to be included with every Unix distribution, so a knowledge of vi, whether or not it is your editor of choice, is recommended.

Each editor is well documented in its man pages, and full books are written about their use. Which is the best for you is a decision only you can make after trying them out. Each has a devoted, almost religious, following.

Some other tools you can use to work with file contents are listed in Table 24-4.

Table 24-4: Text File Tools

Command

Description

Compress

Reduce the size of files by encoding, similar to StuffIt or Zip, but only compresses individual files. Use uncompress to restore the file to its original state. Convention has it that the .z extension indicates a compressed file. To create compressed archives, use tar to create the archive and then compress to reduce its size.

Cut

Selects portions of each line of a file.

Dif

Compares two files.

Fmt

Reformats the files given to have consistent line lengths — default is 65, maximum is 75 characters. This tool originated primarily for the manipulation of line breaks in email messages.

grep

The (in)famous regular expression parser is used to find all instances of patterns within a file or list of files.

Sed

A stream editor, it reads the file(s) specified, modifying the input based upon the command(s) listed and passing the result to standard output. The editing commands may be stored in a file, one per line.

sort

Reorders the lines of a file into a user-defined order. Sort order can be alphabetical, reverse alphabetical, or other combinations.

split

Divides a file into multiple parts, each (except possibly the last part) of the same size. Use cat to recombine the files..

Tar

Creates (uncompressed) archives of the files given as arguments. Short for tape archiver, it is used to package files together.

uniq

Removes duplicate adjacent lines. Pipe the output of sort to uniq if you want to remove all duplicates.

Wc

Reports the number of characters, words, and lines in a file.

Writing shell scripts

You can do more with the shell than just execute commands. The shell has a built-in programming language so that you can write your own text programs or commands. These programs are called shell scripts. The main strength of shell scripts is that you can use them to invoke a possibly long and complex sequence of instructions, with logical branches, as though the sequence were a simple command.

Writing a shell script is similar to entering the commands manually in a Terminal window, with a few significant differences:

  • You may want your command to accept arguments. The shell automatically assigns any strings following your script’s name on the command line to a set of parameters: shell variables named $1 through $9. You don’t have to do anything special to obtain arguments from the command line; they’re already available in the parameter variables when your script begins its execution. If you need more than nine arguments, you can use the shift operator in your script to access later variables.

  • You may want your new command to support options. The shell passes options to your script the same as any other arguments: each command-line string is set into the $n variables (also accessible in the special shell array variable argv[n]).

  • Usually you enter keyboard commands with all information explicitly stated; however, commands inside shell scripts are often parameterized and can be executed conditionally. You parameterize a command by providing variable references and file name substitutions as the command’s arguments instead of literal text. You need to use the shell’s if, switch, while, and foreach commands to handle alternative paths of executions. You rarely use these commands at the keyboard, but they occur often in shell scripts.

Regardless of the use to which you’re going to put a shell script, almost all shell scripts are developed using the following general plan:

  1. Develop a text file containing the required commands.

  2. Mark the text file executable, using the chmod command chmod +x filename to make it executable for all users.

  3. Test the shell script.

  4. Install the script in its permanent location.

  5. Use it.

If the script is for your personal use, create a ~/bin directory and add it to your search path, as described earlier in this Chapter ("Changing shell variables"). After you create a new script, you can just mark the script executable and drop it in your personal bin directory, and it will be available for use.

When testing a script, you may want to see which commands are being executed so that you can track an unexpected behavior. To do so, invoke your script with the command bash –x scriptname or embed a set echo command in your script.

Tip

If you are only interested in a specific range of included commands, you can set echo just before the commands and unset echo immediately after the commands. Remember to remove these set and unset commands after testing.

As with most any other programming language, internal documentation in the form of comments — lines that are not executed but are meant to explain what is going on — is considered very good form. Lines beginning with a splat (MIT jargon for the sharp or number sign character, #) are taken as comments by the shell. In fact, the shell ignores anything starting with a splat to the end of that line as a comment unless the splat is escaped with the backslash character (\).




Mac OS X Bible, Panther Edition
Mac OS X Bible, Panther Edition
ISBN: 0764543997
EAN: 2147483647
Year: 2003
Pages: 290

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net