Unix Overview

This page is a short reference that should contain enough information
to get a new user up and running on a Unix system. 

Topics covered:
  An overview of this document
  A quick look at the command line
  Command line data flow and command execution
  Automatically configuring a process
  Command Line Editing
  Escaping and quoting
  Commands, common ones in alphabetical order
  cron and at
  Shell scripts

  Other sources of Unix information

This is version 1.0.2, 16-MAR-2006

An overview of this document These are the meanings of some special symbols used in this document: % beginning of example command line. % beginning of example command line for a command that is not part of Unix, but is commonly found on such systems. {} indicates the name of a keyboard key, rather than a string to be typed. {ctrl C} indicates that both the control and C keys are pressed together. [] indicates an optional part of the command line. Acronyms are used, but all should be in the glossary. This is version 1.0, dated 15-OCT-2001, and refers to no particular Unix unless specifically stated. Comments, corrections, suggestions, to mathog@caltech.edu back to top of document
A quick look at the command line There is no default shell (command line interpeter) for Unix. Common ones are sh,bash,ksh and csh,tcsh. Except for command line editing and output redirection they all work in more or less the same way. These shells implement a simple computer language, which can be used not only to control the computer interactively, but to write small progams which can be used to automate repetitive tasks. The first group of programs is arguably superior to the second for this application. These are two equivalent forms of the same Unix command: % cat -n out1.txt out2.txt {RETURN} or % cat -n out1.txt \ out2.txt {RETURN} The various pieces are: % Prompt symbol. The computer writes this when it is ready to accept more commands. cat Program to run. This must be located on the user's PATH or contain a full path to the application file. -n Qualifier or parameter which changes the program's actions. out1.txt, out2.txt Parameters, here file specifications. \ As last character on the line, indicates that the command continues on the next line. More generally it tells the shell to escape the next character and not give it any special meaning. {RETURN} Pressing the RETURN key completes the command Unix is usually case sensitive, the whole command line must be specified with exactly the right combination of upper and lower case letters. That is: % CAT -n out1.txt out2.txt {RETURN} will fail because CAT won't find the cat program. Command names in Unix are usually very shortened forms of English words, but there are many exceptions to this rule. back to top of document
Command line data flow and command execution Unix (and C) has three standard or default devices through which it move data. These are: stdin standard input prgram reads data and commands from here stdout standard output program writes data here stderr standard error program writes error messages here In addition most programs accept command line arguments. A great deal of the power of Unix derives from the ability to control the flow of information through these devices. Shells differ slightly in this regard, but in general: % command >file Redirect stdout to file, which is overwritten if it exists and created if it doesn't. For csh derivates stderr redirects as well. % command >>file Redirect stdout to append to file % command <file Read input from file % command1 | command2 Pipe output from command1 into input for command2 % command <<EOD Read as stdin the following lines up to the matching blah terminator is encountered. Pretty much any string blah may be the terminator. EOD % command >>&file csh and derivatives. Redirect both stdout and stderr to the same file % command 2>file sh and derivatives. Redirect stderr to a file. csh and related shells do not allow stderr to be redirected independently of stdout. % command >file 2>&1 sh and derivatives. Redirect both stdout and stderr to the same file % command &>file Additional form provided by bash for redirecting both stdout and stderr to the same file % ( command1 ; command2 ; command3) | command4 In a separate process run the first 3 commands sequentially and pipe the output of the final one into stdin for the fourth command % command <file1 >file2 2>&1 & hook up stdin, stdout, and stderr for the command and run it as a separate process. The prompt will return while this runs in the background. Alternatively, issue the command without the final ampersand, and once it is running press {ctrl-Z} and then give the command bg. % command1 | tee file1 | command2 Pipe the output from command 1 into file1 and as stdin for command2. This is useful for monitoring the progress of a series of commands running in the background since tail file1 will show how far command1 has progressed. % var=`command` Backticks allow stdout from a command to be assigned to a variable. For instance: lastfrank=`ps -ef | grep -i frank | tail -1` will put the final line of the ps output containing "frank" into the variable lastfrank. Backticks work in most (all?) shells but the assignment form varies: var=`command` sh,ksh,bash setenv var `command` csh,tcsh (environmental variable) set var = `command` csh,tcsh (shell variable) back to top of document
Automatically configuring a process Overview When a process is started on an Unix system it runs through a variety of files and executes their contents. In your home directory there will usually be files like .bashrc, .cshrc, etc, which contain shell specific startup commands. Lines beginning with # in this type of shell script are comments. Example .cshrc # # set path and manpath no matter what # setenv PATH /usr/bin:/usr/sbin:/usr/X/bin:/usr/ucb:/usr/ccs/bin:/usr/local/bin setenv MANPATH /usr/man:/usr/local/man:/usr/X/man setenv MAIL /var/mail/$USER # If it's interactive, then set prompt and history if ( $?prompt ) then set history = 200 set prompt="mendel \!% " endif Example .bashrc # User specific aliases and functions alias rm='rm -i' alias cp='cp -i' alias mv='mv -i' # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi export SOMEDIR=/usr/common/thedir export ANOTHERDIR=/usr/local.another back to top of document
Command Line Editing Overview This is very dependent upon the shell you're using. tcsh and bash will generally be configured for you so that you can use the {up arrow} key to recall previous commands and the {left arrow} and {right arrow} keys to move around on a command line. Furthermore, you can reissue previous lines with: % history List previous commands, numbered. Storing such commands may need to be enabled in your own .cshrc or .bashrc if the default system policy does not have this turned on. If the history command doesn't work, neither will the up/down arrow keys nor any of the "!" commands. % !! Execute last command again. % !-3 Execute third command back again. % !5 Execute the fifth command from the history list. Special keys (and related) are: % {up-arrow} Previous command in history list. % {down-arrow} Next command in history list. % {Ctrl C} Terminate running job. % {Ctrl D} Terminate input. % {Ctrl Z} Stop current job, leave it in memory. % bg Used following a {Ctrl Z} to run job in background % {Ctrl S} Stop scrolling. % {Ctrl Q} Resume scrolling. Miscellaneous % {Ctrl 3} ASCII code for {Esc}. % {Ctrl I} ASCII code for {Tab}. back to top of document Escaping and quoting In order to prevent the shell from expanding or substituting on the command line certain characters must be marked off by either by quoting them or "escaping" them (preceding such characters with a "\" character, which means "the next character is not to be treated in any special manner"). If more than one level of escaping/quoting is required the command can become very difficult to understand. For instance, \* escapes the * character but \\\* escapes that character twice. % ls \* Normally * expands to all files in the current directory. This odd example would list a file whose name was "*", which is a bad but legal filename on Unix. % rsh remote echo `hostname` % rsh remote 'echo `hostname`' % rsh remote echo \`hostname\` In the first example the hostname command executes on the local host and the resulting string is substituted into the command line, then the remote host echoes that string. The second and third examples run hostname on the remote host. In other words, the first command emits the local machine name and the second the remote machine name. % rsh remote1 'rsh remote2 echo `hostname` ' % rsh remote1 'rsh remote2 echo \`hostname\` ' % rsh remote1 'rsh remote2 rsh remote3 echo \`hostname\` ' % rsh remote1 'rsh remote2 rsh remote3 echo \\\`hostname\\\` ' In the first example the hostname command runs on remote1, in the second and third on remote2, and in the fourth on remote3 back to top of document
Commands, common ones in alphabetical order Overview This is a list of the commands most likely to be used by nonprivileged users. Commands Actions % apropos (Or man -k). Case insensitive search through man page titles. % cat Type a file or append one or more files to a file. % cd Change directory % cp Copy a file or files (CAREFUL, this overwrites existing targets). % diff Compare two files. % ed Editor (not for beginners - try pico or nedit instead) % elm Mail program - powerful and easy to use % ex Editor (not for beginners - try pico or nedit instead) % find Search for files by property (date, name, size, etc.). % ftp Transfer files to/from another computer. % grep Search files for regular expression (words too), see also fgrep and egrep. % head Show lines from the front of a file (see tail). % history Show previous commands (if enabled in shell). % info Linux/Gnu info utility - get help information on a command. % kill Send a signal to a process (especially "drop dead"). % lp Print a file (SysV unix print command). % lpr Print a file (BSD unix print command). % ls Show files in one or more directories. % mail Mail program - use pine or elm instead. % Mail Mail program - use pine or elm instead. % man Manual page - get help information on a command. % mkdir Create a directory. % more Show text one screenfull at a time. % mv Move a file or files (CAREFUL, this overwrites existing targets). % nedit Editor for X11 sessions - powerful and easy to use % nice Run a command with higher or lower priority (see renice). % passwd Set/reset password on local system (often forbidden). % pdq Print a file (PDQ print system). % pico Editor for terminal sessions - easy to use % pine Mail program - powerful and easy to use % ps Show processes running on the system % pwd Show the current directory % quota -v Show disk quota (if enabled) % rcp Copy a file or files to/from another computer (CAREFUL, this overwrites existing targets). % renice Change the priority of a running process (see nice). % rlogin Login to another computer. % rsh Execute a command on another computer. % rm Remove a file or files. % rmdir Remove a directory. % scp Like rcp, but secure. % set Set (or show) a shell variable. % setenv Set an environmental variable. % ssh Like rsh, but secure. % su Run a shell as another user. % tar Make or restore an archive file, which is one file holding many. % tail Show lines from the end of a file (see head). % talk Talk to someone on another computer (Make or restore an archive file, which is one file holding many. % top Monitor processes running on the system % yppasswd Set/reset network password (often forbidden). % wc Count lines, words, characters in a documnet. back to top of document
Communications Overview Methods of passing data to/from other users on the same or a different computer. This includes file transfers, conversations, determining the status of remote systems, and so forth. In the following machine is either the short or long network name for a remote computer. Actions % finger [user_name]@machine Who is logged on (may be disabled). % ftp machine.subdomain.domain File transfers. % kermit used mostly to automate file downloads, especially through a modem. % netscape Web browser. % opera Web browser. % ping machine test network to remote machine. % rcp filename username@machine:/path/newfilename File transfers. % rlogin -l username machine Login to another system. % rsh -l username command(s) Remote command. % scp filename username@machine:/path/newfilename File transfer - secure. % ssh -l username [command(s)] Remote command or login - secure. % traceroute machine test network to remote machine. % wget URL retrieve files by ftp or http. back to top of document
Devices Overview There are many types of devices available on Unix systems, such as disks, tapes, terminals, printers, and so forth. All of these are accessed through special files which live under /dev. On some Unixes these may be links to other locations. There are no standard naming conventions for either disks or tapes across all Unixes, some typical ones are shown below. Some unixes build the /dev files automatically when new devices are located at boot time, others don't. There is no standard for how these are built but look for a file /dev/MAKEDEV. Device What /dev/null Null device - a void. A place to throw out data /dev/zero Like /dev/null. Reads as end of file. /dev/stdin (On some Unixes). The standard input stream. /dev/stdout (On some Unixes). The standard output stream. /dev/stderr (On some Unixes). The standard error stream. /dev/random (Linux) returns random bytes /dev/nst0 (Linux) the first norewind tape device /dev/nrtape (Irix) a norewind tape device /dev/sda1 (Linux) the second partition on the first SCSI disk /dev/hda1 (Linux) the second partition on the first IDE disk /dev/dsk/dks1d3s7 (Irix) SCSI disk on controller 1, device 3, sector 7 /dev/dsk/c0t0d0s7 (Solaris) IDE or SCSI disk back to top of document
Disks Overview A disk is a special type of device Note that on most Unix systems only privileged users manage disks. The mounting of disks is controlled either by the /etc/fstab file (on Solaris, /etc/vfstab) or by the automounter. File systems may be exported from one machine and mounted on another via the NFS protocol. Disks are usually broken up into 2 or more partitions. Partitions may be used for swap space. If not, a filesystem is created in the partition. There are several different types of file systems available on most Unixes. All of the file systems are mounted in a single hierarchy beneath "/" (root). This hides the disk names from the user - they are essentially never utilized by a normal user, which is one of the biggest differences between unix and most other operating systems. Actions % fdisk (Linux) Tool to partition disks % format (Solaris) Tool to partition disks % fx (Irix) Tool to partition disks % mfks (IRIX) build a new file system % newfs (Solaris) build a new file system % mke2fs (Linux) build a new file system % fsck Check and/or repair a file system. % dump (Exact name varies with Unix). Dump data from a file system, usually for backup purposes. % restore (Exact name varies with Unix). Restore data from a file system, usually for rebuilding a filesystem after a disk failure or other catastrophe. % df -k show all the currently mounted disks % exportfs -a export all entries in /etc/exports % mount /dev/dsk/blah /mnt/point mount the filesystem at /mnt/point % mount -a mount all entries in /etc/fstab % umount /mnt/point unmount the filesystem at /mnt/point % umount -a unmount all entries in /etc/fstab. This often has the side effect of wiping out the special /proc file system and it may not be recreated by umount -a % mntproc (IRIX) remount the /proc file system. For Solaris and Linux /proc is usually listed in /etc/fstab as having the proc filesystem type, so that mount /proc will work. % eject eject media from CDROM or zip drive. Usually it must be dismounted with a umount first. % quota -v Display a user's disk quota (if enabled). If the user area is being served via Samba to Windows machines these values will normally show up under the Total Area and Free Space columns of the "My Computer" window. back to top of document
Directories Overview A directory is a special type of file that contains information about the other files contained within it. Unix in general has no special conventions for such files and they can have essentially arbitrary names. (In rare instances such files may end in ".dir".) Nomenclature . The current directory. .. One level up. ../.. Two levels up. subdir One level down. subdir/subsub two levels down. ~username The user's login directory (shell only). ~ The current user's login directory (shell only). Actions % pwd List the current directory % cd subdir Move into the subdir subdirectory % mkdir subsub Create a subdirectory named subsub % cd .. Move back up to the top % cd subdir/subsub Move into the new subdirectory % cat ~/.cshrc Type your own .cshrc file % cd Go to your login directory % cp ~fred/.cshrc . Copy fred's .cshrc file to your directory, overwriting the existing copy (if any) % du -k Disk usage from the current directory on down, in 1kb units. % rm -r foobar Recursive delete of subdirectory foobar. This is a dangerous command. % rmdir ~fred/woobar Remove fred's (empty) woobar subdirectory back to top of document
Files Unix has very little fixed filename syntax. Unlike VMS, for instance, which has a rigid: NODE"username password"::DEVICE:[DIRECTORY]NAME.EXENSION;VERSION_NUMBER unix files may contain virtually any set of symbols, with the exceptions of "/", the path delimiter, and the ascii character with value 0, which is the end of string delimiter in C. Every part of the filename is case sensitive. A few unixes provide support for file version numbers but this is rarely encountered and/or enabled. Instead version numbers, if present at all, are handled through ad hoc mechanisms within programs and shell scripts. That said, the general Unix file syntax is: [[username@]node:]PATH/filename The username/node parts are only used in those few commands such as rcp which are designed to talk to remote machines. There is no general internode file communication mechanism (similar to DECNET) which will work with arbitrary programs. The PATH consists of something like: [/][dir][/subdir1][/subdir2][/]filename[.extension][.extension] Here are some examples: foobar A file of unknown type subdir/foobar A file in the local subdirectory /subdir/foobar A file in the subdir subdirectory of the root directory foobar.tar Probably a tar file. But maybe not. foobar.tar.gz Probably a gzip'd tar file. foobar.1 Probably Version 1 of foobar, or maybe the man 1 page for foobar /this is a/valid path/with a 1$23.12!~%^&*()3233/but/it's/awful.tar.gz.1.zip This is valid. The horror, the horror... Foobar another file, not another name for foobar, unless one is linked to the other Wild Cards can be used in various positions: * Match anything. Most Unix programs will overwrite without warning existing files if they are specified as an output. Shells in general do the same thing although some have a "noclobber" setting to prevent this. Unix supports file links. That is, a single file may be referenced from more than one location by more than one name. Example: % touch therealone % ln -s therealone SECONDREFERENCE % ln -s $PWD/therealone /tmp/thirdreference % ln -s $PWD/therealone /etc/fouthreference Here one file has four different names scattered across three directories. On some Unixes attempts to remove the real file will fail if the links remain - but on others dangling links will result. The command % ls -al displays file types, ownership, and access permissions. The first character shown indicates the type and is one of: b is a block special file c is a character special file d is a directory D is a door (Solaris) l is a symbolic link m is XENIX shared data (Irix) p is a pipe special file s is a socket (Solaris), XENIX semaphore (Irix) S is a socket (Irix) - is an ordinary file The combination of the file's owner, a group, and protection masks specify who may do what with a file. A few Unixes also support Access Control Lists (ACLs) which offer even finer control over file permissions. The file protection mask has these bits (octal notation) which may be set or reset independently of each other: lists as mask meaning ---s------ 4000 On execution assume UID of file, Owner execution bit set ---S------ Owner execution bit clear. ------s--- 20#0 On execution assume GID of file, Group execution bit set ------S--- Group execution bit clear. drwxrwxrwt 1000 Enable sticky bit. Changes directory permissions so that only a file's creator may remove it. Used primarily for the /tmp and other shared directories. -r-------- 0400 Owner may read --w------- 0200 Owner may write ---x------ 0100 Owner may execute. For directories, allows listing of contents. ----r----- 0040 Group may read -----w---- 0020 Group may write ------x--- 0010 Group may execute. For directories, allows listing of contents. -------r-- 0004 Others may read --------w- 0002 Others may write ---------x 0001 Others may execute. For directories, allows listing of contents. ##########+ ACL is defined (POSIX syntax) ########## ACL is not defined (POSIX syntax) Actions % cat >afile <<EOD some text to put in this file EOD % cp afile bfile make a copy % cat afile >>bfile append a second copy to the first % rm afile delete the original % cat bfile view the result % more bfile view the result one page at a time % ls *file* list all files in this directory containing the string "file" in their name % find . -name '*file*' -print find all files in this directory and down containing the string "file" in the name % wc <bfile characters,words,lines in bfile % pico bfile edit bfile in a terminal session. Other editors are ex,ed,edit,vi,emacs, etc. % nedit bfile edit bfile in an X11 session. % grep "a string" * look for the text "a string" in all files in the current directory % stat bfile some properties of bfile % ls -al bfile some other properties of bfile % lsof | grep bfile who/what is using bfile? % od bfile octal dump of bfile % ls -al bfile list ownership and permissions -rw-r--r-- 1 fred students 485 Oct 16 09:36 bfile % chown ginger.profs bfile change owner (on Solaris it's ginger:profs) % chmod 504 bfile change permissions % ls -al bfile -r-x---r-- 1 ginger profs 485 Oct 16 09:36 bfile % umask 500 set the default file permission mask % touch cfile create a file % ls -al bfile -r-x------ 1 freg students 0 Oct 16 09:37 cfile % rm -r * Wipes out everything in this directory and below. Wild cards with rm can be a very dangerous mix. If you must do that always do an equivalent ls command first, just to make sure you hit the files that you expect. It's possible to accidentally generate a file with an unprintable name, or one beginning with a dash, either of which is extremely difficult to remove using normal Unix commands. If this happens there are a few tricks to fall back on to remove the offending file. These are: % touch foobar % rm foobar -badname Sometimes this coerces rm into ignoring -. Otherwise there will be an error when rm thinks -badname is a command line argument or % ls -i1 list inode numbers for all files, assume that 66666 is the inode number of the bad file % find -inum 66666 -exec rm '{}' \; find file by its inode number and then feed the resulting name into rm. This happens in a manner that does not go through the shell, so it works even when you could not rm the filename from the command line. or % rm -ri . Answer no until you reach the bad file, then answer yes or % rm -i *match* If some part of the name is visible and unique use it to pull out the full filename and get a prompt to remote it. This will NOT work if the bad file begins with a - as *match* literally expands all matching files on the command line and is in that sense no different than typing in the one file name. back to top of document
Help The on line documenation may be accessed from the command line with one of the commands below. It is very common for there to be HTML and PDF documentation but there is absolutely no standard for its location. Various ways of accessing on line help. % apropos string % man -k string List man pages that contain string in their titles. % man subject View a man page. If the MANPATH variable is not set correctly the page will not be found. Typically MANPATH will contain these directories: /usr/man /usr/local/man /usr/share/man /usr/X/man % help Sometimes the same thing as man % info subject GNU info utility. back to top of document
MAIL Unix comes with two simple mail client programs called mail and Mail. Unless you're a total masochist you do not want to use either one. Additionally, many Unix machines act as mail servers using either the sendmail program or one of many freely available replacements for it. Configuring a mail server is beyond the scope of this document. However, if your Unix machine is not going to be a mail server be sure to configure it to not start the sendmail daemon. Historically sendmail has been the source of many security problems - if you can live without it, do so. % mail get a life! % MAIL % pine A reasonable command line mail client % elm Another good mail client % mutt Yet another - but not as common as the preceding two % netscape The Netscape mail client will function on any platform where this program runs. A mail server is required and it may be either local or run on a remote machine. back to top of document
Processes Overview Each process has a unique PID through which it may be controlled. There is one foreground process for each interactive session. There may be an unlimited number of background processes (up to memory and CPU limitations.) Actions % bg Continue running the halted program in the background % fg pid Move a background job into the foreground % jobs Show all processes for the current session % kill -9 pid Kill the process associated with that pid % nice -5 command Run command at a slightly reduced priority % ps -ef List all processes % renice +5 pid Reduce priority on a running process % top Monitor processes {c} Kill the currently running program {Z} Halt the currently running program % wait pid Wait until the background job with the % echo $? specified PID exits and then echo its exit status. If pid is omitted then wait for all background jobs to exit and return a status of 0. Bash won't wait on a stopped job. back to top of document
cron and at Most Unix systems do not have formal batch Queues enabled. Instead they use cron to schedule jobs which run at particular times, and at to schedule jobs to run once at a particular time. Refer to the relevant man pages for more information. back to top of document
Variables Variables are used to store data within a shell. They can also be used for a variety of manipulations which are most commonly found within command procedures, such as adding integers, creating filenames, editing text and so forth. Variable manipulation is highly shell dependent. Nomenclature avar=string sh and related. Define a variable within the currently executing shell script. It will not be visible to subsequent commands. export avar=string sh and related. Define a variable within the currently executing shell script AND make it visible to subsequent commands. set avar = string csh and related. Define a shell variable setenv avar string csh and related. Define an environmental variable % command ${avar} substitute the value for avar and then run the command % command $avar The first form is used in situations where the shell needs help figuring out where the end of "avar" is, for instance: % export avar=foobar % command ${avar}woo is equivalent to % command foobarwoo but % command $avarwoo will generate an error as no variable avarawoo exists. sh/bash special variables $1, $2, .. The values of the parameters passed to a shell script $# The number of parameters which were passed $* (bash only) Expands to the script parameters, starting from one, separated by the IFS character. $@ (bash only) Expands like $* but into separate tokens as seen by the shell $? Status of the previous command executed $- Shell option flags currently set, by the set builtin $$ Process ID of the shell or top process shell (for sub processes) $! Process ID of the most recent background command $0 (bash only) Interactive: name of the shell; in a script: script's name. ${parameter:Xword} conditional substitition. X Action - If parameter is good use it, else, use word = If parameter is bad use word ? If parameter is good use it, else print a warning + If parameter is good use word, else do nothing A parameter is "good" if it is set and not an empty string. If the expression does not require that word be evaluated, it will not be. Example: echo ${alreadyintemp-`cd /tmp`} >/dev/null csh special variables (shell variable operations only) $1, $2, .. The values of the parameters passed to a shell script, also corresponds to the words in a variable "argv". $#name The number of words stored in variable "name" $name[range] Extract one or more words using the range as indices. Words are numbered from 1 to N. A range may be either a single index such as [4], a full range, like [2-5], or a half range, like [1-] or [-5]. These are equivalent to [1-N] and [1-5]. $* All words in argv. ${name:modifier} Process the variable name according to ONE (and only one) of these modifiers: h /foo/woo.blah -> /foo r /foo/woo.blah -> /foo/woo e /foo/woo.blah -> blah t /foo/woo.blah -> woo.blah q Prevent further substitutions on this variable x Like q, but break into words at each space character, tab or newline. back to top of document
Shell scripts Shells scripts are used to automate certain tasks. Here is a small example shell script which doesn't do much of anything beyond demonstrating some of the more common constructs. #!/bin/bash # The preceding line instructs the system to use bash to run # this script. It must be the very first line. To enable debugging # Use instead #!/bin/bash -x # # echo the command line arguments, if any # echo Running Script $0 if [ $# -gt 0 ] then echo " with arguments: $*" else echo " with arguments: (none)" fi # # or do it this way instead # echo "Number of command line arguments: $#" count=1 for d in $* do echo "argument $count is $d" count=`expr $count + 1` done # # The #$&#($& Bash man page doesn't make this clear but if you use # the string comparison operators < and > they must be escaped. In the # following example the first one works and the second one doesn't. # if [ "one1" \< "one2" ] then echo "this comparison worked as expected" else echo "this comparison did NOT work as expected" fi if [ "one1" < "one2" ] then echo "this comparison worked as expected" else echo "this comparison did NOT work as expected" fi # # using eval to force multiple levels of substitution # here $number from $`echo $count` is further substituted # because of the eval # while [ $count -gt 1 ] do count=`expr $count - 1` eval echo "argument $count is $`echo $count`" done # echo "Processes owned by root:" echo "PID program" /bin/ps -ef | while read OWNER P1 P2 P3 P4 P5 P6 P7 ; do if [ $OWNER = 'root' ] then echo $P1 $P7 fi done # # testing on file conditionals # if [ -d /etc ] then echo "/etc directory exists" else echo "/etc directory does not exist" fi # if [ -x /etc ] then echo "/etc has executable bit set" else echo "/etc does not have executable bit set" fi # # some logicals # iamtrue=1 iamfalse=0 if [ $iamtrue -eq 1 ] then echo "right" else echo "wrong" fi if [ \( $iamtrue -eq 1 \) -a \( $iamfalse -eq 1 \) ] then echo "wrong" else echo "right" fi if [ \( $iamtrue -eq 1 \) -o \( $iamfalse -eq 1 \) ] then echo "right" else echo "wrong" fi if [ ! $iamtrue -eq $iamfalse ] then echo "right" else echo "wrong" fi # # The "case" structure # case $# in 0) echo no command line arguments ;; 1) echo one command line argument ;; 2) echo two command line arguments ;; *) echo more than two command line arguments ;; esac # # example of set # set `uname -a` echo "set from uname had $# values" echo " first was: $1" echo " second was: $2" # # example of a subroutine - normally this would be placed nearer to the # top of the script. Note that within this function $1 etc are those of # of the function, not the script as a whole. The two expansions show # how to do an indexed access in the bourne shell and also the difference # between an $* expanstion and the $1, $2, $3, $4 expansion. # multiecho () { echo "Number of function arguments: $#" echo "expanding \$1, \$2, \$3, etc." maxcount=$# count=1 while [ $count -le $maxcount ] do thedollar=$`echo $count` thevalue=`eval echo $thedollar` echo " function argument $count is $thevalue" count=`expr $count + 1` done # echo "expanding \$*" count=1 for d in $* do echo " function argument $count is $d" count=`expr $count + 1` done } multiecho first second third 'fourth is all of this' # # generally "exit" is the way to unconditionally leave a script. However # if a script is to be run using the ". filename" syntax then it # runs in the context of the current process which will terminate # when the script does "exit". This is rarely the desired action. # For BASH in these situations use "return" instead of "exit". exit back to top of document
X11 Overview The X11 window system is Graphical User Interface somewhat similar to that present on Windows and Macintosh machines. The most important difference being that an X11 display (confusingly, the server) may be controlled by a remote program (the client). The shell variable DISPLAY controls where a program sends its display. Some X11 programs can override this variable with a command line option. Access control is determined by the xauth and xhost mechanisms. Limit access to only those machines which must have it - otherwise it is possible for hackers to read your display. Actions % export DISPLAY=machine:0.0 (sh) Set the output display % set DISPLAY = machine:0.0 (csh) Set the output display % xhost +remote1 % xhost -remote2 Allow/disallow access from these machines % xauth Another method to allow/disallow access % xdpyinfo Information about the X11 display. Often helpful in debugging display problems % xterm X11 terminal emulator. back to top of document
Glossary GID Group identification GUI Graphical User Interface IFS Internal Field Separator. This special variable holds the list of characters which can delimit tokens on a command line. The first character of the IFS is used to separate tokens generated by replacements such as $*. PID Process identifier UID User identification Signal A simple type of message which may be sent to a program. It consists of a single integer value. The program may or may not honor all signals but usually will die if sent SIGKILL (=9). Shell A program which runs and controls programs. X11,XWindows A Graphical User Interface employed on Unix and some other systems. back to top of document
Other sources of information on Unix Too many to list. back to top of document