Вы находитесь на странице: 1из 19

By: Himanshu Aggarwal B.

Tech CS&E CS-5(Y) A2305208594 Roll no: 533

Introduction
UNIX is a computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna. Today the term UNIX is used to describe any operating system that conforms to UNIX standards, meaning the core operating system operates the same as the original UNIX operating system. Today's UNIX systems are split into various branches, developed over time by AT&T as well as various commercial vendors and non-profit organizations UNIX operating systems are widely used in both servers and workstations. The UNIX environment and the client-server program model were essential elements in the development of the Internet and the reshaping of computing as centered in networks rather than in individual computers. Both UNIX and the C programming language were developed by AT&T and distributed to government and academic institutions, which led to both being ported to a wider variety of machine families than any other operating system. As a result, UNIX became synonymous with "open systems. UNIX was designed to be portable, multi-tasking and multi-user in a time-sharing configuration. UNIX systems are characterized by various concepts: the use of plain text for storing data; a hierarchical file system; treating devices and certain types of inter-process communication (IPC) as files; and the use of a large number of software tools, small programs that can be strung together through a command line interpreter using pipes, as opposed to using a single monolithic program that includes all of the same functionality. These concepts are known as the UNIX philosophy. Under UNIX, the "operating system" consists of many of these utilities along with the master control program, the kernel. The kernel provides services to start and stop programs, handles the file system and other common "low level" tasks that most programs share, and, perhaps most importantly, schedules access to hardware to avoid conflicts if two programs try to access the same resource or device simultaneously. To mediate such access, the kernel was given special rights on the system, leading to the division between user-space and kernel-space. The microkernel concept was introduced in an effort to reverse the trend towards larger kernels and return to a system in which most tasks were completed by smaller utilities. In an era when a "normal" computer consisted of a hard disk for storage and a data terminal for input and output (I/O), the UNIX file model worked quite well as most I/O was "linear". However, modern systems include networking and other new devices. As graphical user interfaces developed, the file model proved inadequate to the task of handling asynchronous events such as those generated by a mouse, and in the 1980s non-blocking I/O and the set of inter-process communication mechanisms was augmented (sockets, shared memory, message queues, semaphores), and functionalities such as network protocols were moved out of the kernel.

The UNIX system is composed of several components that are normally packaged together. By including in addition to the kernel of an operating system the development environment, libraries, documents, and the portable, modifiable source-code for all of these components, UNIX was a self-contained software system. This was one of the key reasons it emerged as an important teaching and learning tool and has had such a broad influence. The inclusion of these components did not make the system large the original V7 UNIX distribution, consisting of copies of all of the compiled binaries plus all of the source code and documentation occupied less than 10MB, and arrived on a single 9-track magnetic tape. The printed documentation, typeset from the on-line sources, was contained in two volumes. The names and file system locations of the UNIX components have changed substantially across the history of the system. Nonetheless, the V7 implementation is considered by many to have the canonical early structure:

Kernel source code in /usr/sys, composed of several sub-components:  conf configuration and machine-dependent parts, including boot code  dev device drivers for control of hardware (and some pseudo-hardware)  sys operating system "kernel", handling memory management, process scheduling, system calls, etc.  h header files, defining key structures within the system and important system-specific invariables Development Environment Early versions of UNIX contained a development environment sufficient to recreate the entire system from source code:  cc C language compiler (first appeared in V3 UNIX)  as machine-language assembler for the machine  ld linker, for combining object files  lib object-code libraries (installed in /lib or /usr/lib) libc, the system library with C run-time support, was the primary library, but there have always been additional libraries for such things as mathematical functions (libm) or database access. V7 UNIX introduced the first version of the modern "Standard I/O" library stdio as part of the system library. Later implementations increased the number of libraries significantly.  make build manager (introduced in PWB/UNIX), for effectively automating the build process  include header files for software development, defining standard interfaces and system invariants  Other languages V7 UNIX contained a Fortran-77 compiler, a programmable arbitraryprecision calculator (bc, dc), and the awk "scripting" language, and later versions and implementations contain many other language compilers and toolsets. Early BSD releases included Pascal tools, and many modern UNIX systems also include the GNU Compiler Collection as well as or instead of a proprietary compiler system.  Other tools including an object-code archive manager (ar), symbol-table lister (nm), compilerdevelopment tools (e.g. lex & yacc), and debugging tools. Commands UNIX makes little distinction between commands (user-level programs) for system operation and maintenance (e.g. cron), commands of general utility (e.g. grep), and more generalpurpose applications such as the text formatting and typesetting package. Nonetheless, some major categories are:  sh The "shell" programmable command line interpreter, the primary user interface on UNIX before window systems appeared, and even afterward (within a "command window").  Utilities the core tool kit of the UNIX command set, including cp, ls, grep, find and many others. Subcategories include:  System utilities administrative tools such as mkfs, fsck, and many others  User utilities environment management tools such as passwd, kill, and others.  Document formatting UNIX systems were used from the outset for document preparation and typesetting systems, and included many related programs such as nroff, troff, tbl, eqn, refer, and pic. Some modern UNIX systems also include packages such as TeX and Ghostscript.  Graphics the plot subsystem provided facilities for producing simple vector plots in a deviceindependent format, with device-specific interpreters to display such files. Modern UNIX systems also generally include X11 as a standard windowing system and GUI, and many support OpenGL.  Communications Early UNIX systems contained no inter-system communication, but did include the inter-user communication programs mail and write. V7 introduced the early intersystem communication system UUCP, and systems beginning with BSD release 4.1c included TCP/IP utilities. Documentation UNIX was the first operating system to include all of its documentation online in machine-readable form. The documentation included:  man manual pages for each command, library component, system call, header file, etc.  doc longer documents detailing major subsystems, such as the C language and troff

UNIX is a case sensitive OS.

Unix command
All the User Commands in UNIX are entered in Lower Case while the System Commands are entered in Upper Case. All commands are executed after the $ symbol in UNIX interface. This $ sign will appear when you have successfully logged into the UNIX interface (i.e. after successful authentication of username and password). This symbol means the interface is ready to take commands from user and process them. To log out of UNIX [ctrl d] is pressed. Here is the list of various UNIX commands: y Logging out of UNIX  $ [ctrl d] Press ctrl d at any instant of runtime of UNIX to exit from the current running utility, program or software. If the interface is Idle and these keys are pressed then the operating system is logged out.  $ logout This command is used to logout from UNIX at any moment of time.  $ exit This command is same as the [ctrl d] function keys. y Changing Password  $ passwd This command is used to change the password of the currently logged in user. Syntax: $ passwd Old Password: New Password: Re-enter New Password: y Information Commands:  $ who Checking the users who are on the stream along with you. Syntax: $ who  $ who am I This command is used to get self details like username, terminal name, date time etc. Syntax: $who am i  $ echo $ SHELL This command is used to check the shell type. Syntax: $echo$SHELL /bin/ksh where ksh tells the shell type.  $ echo $ TERM This Command is used to check the terminal type.

Syntax: $echo$TERM ansi this is the terminal type.  $ SET This system command is used to determine all system variables (commands) in one go. Syntax: $SET CD PATH: HOME: HOST NAME: MAIL: PATH: SHELL:  $ tty This Command is used to check the user terminal. Syntax: $tty

Files & Directory Commands of UNIX :  $ mkdir This command is used to make a new directory (i.e. folder) in the current directory Syntax: $mkdir <directory name> $mkdir docs this will create a directory named docs in the current root location.

Attributes: $ mkdir patch patch attribute is used to create 2 directories symultaniously. Syntax: $mkdir patch <directory_name1> <directory_name2> $mkdir patch dis doc here dis and doc are two different directories. $ mkdir pis pis/prog pis/data this syntax is used to make a parent directory (here pis) and simultaneously add its sub directories. Note: $mkdir will show errors when: 1. There is file with same name under current directory. 2. There is directory with same name under current directory. 3. If the directory dont have the access rights.

 $ rmdir This command is used to delete (remove) the directory from the current part (or directory). Syntax: $rmdir <directory_name>  $ cp This command is used to copy a file or a folder to a particular destination. Syntax: $cp <File/Directory1(source)> <File/Directory2(destination)> $cp chap1 chap2 This will copy chap1 to chap2. To Copy multiple files: $cp <file/dir1> <file/dir2> <destination_folder>  $ pwd This command is used to see the current directory (or path) the user is working in. Syntax: $pwd /home/array/progs  $ cd This command is used to change the directory(i.e. from current to another sub or parent directory). Syntax: $cd .. This will change the directory to parent directory. $cd . This will cange to a level up directory. E.g: $pwd /home/array/prgs $cd .. /home/array Attributes for directory commands: 1. -i it asks for overwriting <yes/no> 2. r it iterates the commands executed. 3. f this will overwrite the write protection 4. * - this is used for applying a command for all files in a directory. Note: any of the two or more attributes can be used at once in the unix commandline interface. y Other Important UNIX commands:  $ clear This command is used to clear the screen.

Syntax: $clear  $ tput This command is used to position the cursor. Syntax: $tput cup <row> <column> $tput cup 10 20 This will place the cursor to 10th row and 20th column on the screen.  $ date- this command is used to see the current date. Syntax: $date Sun Nov 08 23:03:34 IST 2009  $ cal this command is used to see the calendar for a specific month or year. Syntax: $cal dec this will display the calendar for the month of December of current year.  $ cat This command is used to viewing/creating a file. Syntax: $cat >fox Abc123. [ctrl d] $cat fox Abc123  $ bc This command is used to open the calculator. Its basically the calculator of UNIX. Syntax: $bc 12+4 16  $ man This command is used for viewing the documentation and manual pages of UNIX. It contains the online manual of all the UNIX commands. It provides documentation, licencing and terms of use about the UNIX. Syntax: $man Attributes: 1. $man more - Shows the manual page wise.

2. $man 10f/b takes the manual 10 pages (f) forward/ (b) backward from the current page position. 3. $man q Quits the manual and returns to the pervious state.  $ wc This command counts the number of words in a file. Wc stands for word count. Syntax: $wc <filename> 2 5 26 <filename> - this is the form of output here 2 is the number of line, 5 is the number of words, 26 is the number of character.  $ LP this system command is used for line printing. This commands sends a file to the print queue. Syntax: $LP <filename> O/p: Request id is pl-320.  $ cancel this command cancels a job. Syntax: $cancel <filename>  $ df - this command tells the user the amount of free space available on the physical storage device ( i.e. Free space on the disk.) Syntax: $df  $ du this command tells the amount of disk space used. Syntax: $du  $ ls this command is used to list the files and folders stored in the current directory. Syntax: $ls Attributes: 1. 2. 3. 4. 5. 6. x it is used to display multi column output. F it is used to mark executables with *, directories with /, symbols links with @. a it is used for all header files. R It is used to recursively show all the files of directory & sub-directory. d It is used to show all sub-directories. t it shows the last item of modification.

7. i this attribute shows the inode number 8. s it shows the file size in kb blocks. 9. r it shows the output in reverse alphabetical order.  Printing Files: 1. $lpr To queue the files to the printer. 2. $lpq To Display the status of the print queue. 3. $lpmr To cancel the print job.  $ chmod This command is used to change the file permission. Chmod stands for change mode. Syntax: $chmod <mode> <filename> Modes: 1. U Owner. 2. G Group. 3. R Others. 4. T Add Permission. 5. - Remove Permission 6. = Clear Permission and set to mode specified. y VI Editor Commands:  $vi <new_file_name> : this command starts a new file editing in the VI Editor. Vi Editor is a full screen editor. It helps in creating and editing files. It has following tow modes of operation (listed along with its commands):  Command Mode: 1. a Append text alter cursor 2. A append text at the end of the line. 3. i Insert text at the cursor. 4. l insert txet at the beginning of the file. 5. o add an empty line under the cursor. 6. O add an empty line above cursor. 7. s substitute a character with text. 8. :q quiting without saving 9. :w saving without exiting. 10. :wq saving and exiting. 11. :x save and exit. 12. Zz save and exit. 13. /line searches forward for the first occurance of the word line. 14. ?line searches forward for the occurance of the word line. 15. n Continue the search in the same direction. 16. N- continue the search in the opposite direction. 17. :!<UNIX COMMANDS> - for executing UNIX commands in VI EDITOR. 18. :g/line/s//LINE/g This command is used in VI EDITOR to find and replace the occurance of word line by the word LINE here s stands for sub-title, g stands for global(i.e. itll change all words line by LINE). 19. dd - Cut a range of lines ( e.g. 12dd cuts 12 lines from the current cursor position.) 20. p - paste at the current cursor position. 21. U undo the changes. 22. yy- Copy the text from the current cursor position.  Text Mode: 1. x To delete a single character.

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. y Pipe :

dw To delete at the end of the current word. d$ To delete to the end of the line. d0 To delete to the start of the line. dd To delete the whole line. :20,40d To delete a range of lines. Rnewtext To replace old text by overwriting. c2w Change to the end of the next word. v undo the last change. Ctrl-b,h,k cursor movement up. 0-b,h,b cursor movement left. $-w,w,l - cursor movement right. f.l, crtl+,g cursor movement down.

A sequence of two or more commands separated by a vertical bar is called as a pipe. Standard output of each command becomes the standard input for the next command. E.g.: $ls-l/wc-l Output generated by the execution of command ls-l becomes the input for the command wc-l. these two commands are joined by/ called the pipe. y Tee command: It reads the standard input and sends the data to both the standard output and the file. Syntax: $ls/tee ls.save/wc-l This will read the output from command ls and tee command will send the output to monitor (standard output device) and along with it the output will be saved in the file named ls.save and then its word count will be done by the wc command.

What is vi?
The default editor that comes with the UNIX operating system is called vi (visual editor). [Alternate editors for UNIX environments include pico and emacs, a product of GNU.] The UNIX vi editor is a full screen editor and has two modes of operation: 1. Command mode commands which cause action to be taken on the file, and 2. Insert mode in which entered text is inserted into the file. In the command mode, every character typed is a command that does something to the text file being edited; a character typed in the command mode may even cause the vi editor to enter the insert mode. In the insert mode, every character typed is added to the text in the file; pressing the <Esc> (Escape) key turns off the Insert mode. While there are a number of vi commands, just a handful of these is usually sufficient for beginning vi users. To assist such users, this Web page contains a sampling of basic vi commands. The most basic and useful commands are marked with an asterisk (* or star) in the tables below. With practice, these commands should become automatic.

To Get Into and Out Of vi


To Start vi To use vi on a file, type in vi filename. If the file named filename exists, then the first page (or screen) of the file will be displayed; if the file does not exist, then an empty file and screen are created into which you may enter text. * vi filename edit filename starting at line 1
vi -r filename recover filename that was being edited when system crashed

To Exit vi Usually the new or modified file is saved when you leave vi. However, it is also possible to quit vi without saving the file. * :x<Return> quit vi, writing out modified file to file named in original invocation
:wq<Return> quit vi, writing out modified file to file named in original invocation :q<Return>

quit (or exit) vi

* :q!<Return> quit vi even though latest changes have not been saved for this vi call

Screen Manipulation
The following commands allow the vi editor screen (or window) to move up or down several lines and to be refreshed. ^f move forward one screen
^b move backward one screen ^d move down (forward) one half screen ^u move up (back) one half screen ^l redraws the screen ^r redraws the screen, removing deleted lines

Inserting or Adding Text The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text and to put the vi editor back into command mode. * i insert text before cursor, until <Esc> hit
I insert text at beginning of current line, until <Esc> hit

* a append text after cursor, until <Esc> hit


A append text to end of current line, until <Esc> hit

* o open and put text in a new line below current line, until <Esc> hit

* O open and put text in a new line above current line, until <Esc> hit Deleting Text The following commands allow you to delete text. delete single character under cursor *x
Nx dw dNw D

delete N characters, starting with character under cursor delete the single word beginning with character under cursor delete N words beginning with character under cursor; e.g., d5w deletes 5 words delete the remainder of the line, starting with current cursor position delete entire current line delete N lines, beginning with the current line; e.g., 5dd deletes 5 lines

* dd
Ndd or dNd

Saving and Reading Files


These commands permit you to input and output files other than the named file with which you are currently working.
:r filename<Return> :w<Return> :w newfile<Return>

read file named filename and insert after current line (the line with cursor) write current contents to file named in original vi call write current contents to a new file named newfile

:w! prevfile<Return> write current contents over a pre-existing file named prevfile

Shell Introduction
The shell is both a command language and a programming language that provides an interface to the UNIX operating system. This memorandum describes, with examples, the UNIX shell. The first section covers most of the everyday requirements of terminal users. Some familiarity with UNIX is an advantage when reading this section; see, for example, "UNIX for beginners". Section 2 describes those features of the shell primarily intended for use within shell procedures. These include the control-flow primitives and string-valued variables provided by the shell. A knowledge of a programming language would be a help when reading this section. The last section describes the more advanced features of the shell. References of the form "see pipe (2)" are to a section of the UNIX manual.

Simple commands
Simple commands consist of one or more words separated by blanks. The first word is the name of the command to be executed; any remaining words are passed as arguments to the command. For example,
who

is a command that prints the names of users logged in. The command
ls -l

prints a list of files in the current directory. The argument -l tells ls to print status information, size and the creation date for each file.

The shell and login


Following login (1) the shell is called to read and execute commands typed at the terminal. If the user's login directory contains the file .profile then it is assumed to contain commands and is read by the shell before reading any commands from the terminal.

Summary
ls Print the names of files in the current directory. ls >file Put the output from ls into file. ls | wc -l Print the number of files in the current directory. ls | grep old Print those file names containing the string old. ls | grep old | wc -l Print the number of files whose name contains the string old. cc pgm.c & Run cc in the background.

Shell procedures
The shell may be used to read and execute commands contained in a file. For example,
sh file [ args ... ]

calls the shell to read commands from file. Such a file is called a command procedure or shell procedure. Arguments may be supplied with the call and are referred to in file using the positional parameters $1, $2, .... For example, if the file wg contains
who | grep $1

then
sh wg fred

is equivalent to
who | grep fred

UNIX files have three independent attributes, read, write and execute. The UNIX command chmod (1) may be used to make a file executable. For example,
chmod +x wg

will ensure that the file wg has execute status. Following this, the command
wg fred

is equivalent to
sh wg fred

This allows shell procedures and programs to be used interchangeably. In either case a new process is created to run the command.

As well as providing names for the positional parameters, the number of positional parameters in the call is available as $#. The name of the file being executed is available as $0.

A special shell parameter $* is used to substitute for all positional parameters except $0. A typical use of this is to provide some default arguments, as in,
nroff -T450 -ms $*

which simply prepends some arguments to those already given.

Control flow - for


A frequent use of shell procedures is to loop through the arguments ($1, $2, ...) executing commands once for each argument. An example of such a procedure is tel that searches the file /usr/lib/telnos that contains lines of the form
... fred mh0123 bert mh0789 ...

The text of tel is


for i do grep $i /usr/lib/telnos; done

The command
tel fred

prints those lines in /usr/lib/telnos that contain the string fred.


tel fred bert

prints those lines containing fred followed by those for bert.

The for loop notation is recognized by the shell and has the general form
for name in w1 w2 ... do command-list done

A command-list is a sequence of one or more simple commands separated or terminated by a newline or semicolon. Furthermore, reserved words like do and done are only recognized following a newline or semicolon. name is a shell variable that is set to the words w1 w2 ... in turn each time the command-list following do is executed. If in w1 w2 ... is omitted then the loop is executed once for each positional parameter; that is, in $* is assumed.

Another example of the use of the for loop is the create command whose text is
for i do >$i; done

The command
create alpha beta

ensures that two empty files alpha and beta exist and are empty. The notation >file may be used on its own to create or clear the contents of a file. Notice also that a semicolon (or newline) is required before done.

Control flow - case


A multiple way branch is provided for by the case notation. For example,
case $# 1) 2) *) esac in cat >>$1 ;; cat >>$2 <$1 ;; echo \'usage: append [ from ] to\' ;;

is an append command. When called with one argument as


append file

$# is the string 1 and the standard input is copied onto the end of file using the cat command.

append file1 file2

appends the contents of file1 onto file2. If the number of arguments supplied to append is other than 1 or 2 then a message is printed indicating proper usage.

The general form of the case command is


case word in pattern) command-list;; ... esac

The shell attempts to match word with each pattern, in the order in which the patterns appear. If a match is found the associated command-list is executed and execution of the case is complete. Since * is the pattern that matches any string it can be used for the default case.

A word of caution: no check is made to ensure that only one pattern matches the case argument. The first match found defines the set of commands to be executed. In the example below the commands following the second * will never be executed.
case $# in *) ... ;; *) ... ;; esac

Another example of the use of the case construction is to distinguish between different forms of an argument. The following example is a fragment of a cc command.
for i do case $i in -[ocs]) ... ;; -*) echo \'unknown flag $i\' ;; *.c) /lib/c0 $i ... ;; *) echo \'unexpected argument $i\' ;; esac done

To allow the same commands to be associated with more than one pattern the case command provides for alternative patterns separated by a |. For example,
case $i in -x|-y) esac ...

is equivalent to
case $i in -[xy]) esac case $i in \?) ...

The usual quoting conventions apply so that


...

will match the character ?.

Shell variables
The shell provides string-valued variables. Variable names begin with a letter and consist of letters, digits and underscores. Variables may be given values by writing, for example,
user=fred box=m000 acct=mh0000

which assigns values to the variables user, box and acct. A variable may be set to the null string by saying, for example,
null=

The value of a variable is substituted by preceding its name with $; for example,

echo $user

will echo fred.

Variables may be used interactively to provide abbreviations for frequently used strings. For example,
b=/usr/fred/bin mv pgm $b

will move the file pgm from the current directory to the directory /usr/fred/bin. A more general notation is available for parameter (or variable) substitution, as in,
echo ${user}

which is equivalent to
echo $user

and is used when the parameter name is followed by a letter or digit. For example,
tmp=/tmp/ps ps a >${tmp}a

will direct the output of ps to the file /tmp/psa, whereas,


ps a >$tmpa

would cause the value of the variable tmpa to be substituted.

Except for $? the following are set initially by the shell. $? is set after executing each command.
$? The exit status (return code) of the last command executed as a decimal string. Most commands return a zero exit status if they complete successfully, otherwise a non-zero exit status is returned. Testing the value of return codes is dealt with later under if and while commands. $# The number of positional parameters (in decimal). Used, for example, in the append command to check the number of parameters. $$ The process number of this shell (in decimal). Since process numbers are unique among all existing processes, this string is frequently used to generate unique temporary file names. For example,
ps a >/tmp/ps$$ ... rm /tmp/ps$$

$! The process number of the last process run in the background (in decimal). $The current shell flags, such as -x and -v. Some variables have a special meaning to the shell and should be avoided for general use. $MAIL When used interactively the shell looks at the file specified by this variable before it issues a prompt. If the specified file has been modified since it was last looked at the shell prints the message you have mail before prompting for the next command. This variable is typically set in the file .profile, in the user's login directory. For example,
MAIL=/usr/mail/fred

$HOME The default argument for the cd command. The current directory is used to resolve file name references that do not begin with a /, and is changed using the cd command. For example,
cd /usr/fred/bin

makes the current directory /usr/fred/bin.

cat wn

will print on the terminal the file wn in this directory. The command cd with no argument is equivalent to
cd $HOME

This variable is also typically set in the the user's login profile. $PATH A list of directories that contain commands (the search path). Each time a command is executed by the shell a list of directories is searched for an executable file. If $PATH is not set then the current directory, /bin, and /usr/bin are searched by default. Otherwise $PATH consists of directory names separated by :. For example,
PATH=:/usr/fred/bin:/bin:/usr/bin

specifies that the current directory (the null string before the first :), /usr/fred/bin, /bin and /usr/bin are to be searched in that order. In this way individual users can have their own `private' commands that are accessible independently of the current directory. If the command name contains a / then this directory search is not used; a single attempt is made to execute the command. $PS1 The primary shell prompt string, by default, `$ '. $PS2 The shell prompt when further input is needed, by default, `> '. $IFS The set of characters used by blank interpretation (see section 3.4).

The test command


The test command, although not part of the shell, is intended for use by shell programs. For example,
test -f file

returns zero exit status if file exists and non-zero exit status otherwise. In general test evaluates a predicate and returns the result as its exit status. Some of the more frequently used test arguments are given here, see test (1) for a complete specification. test s true if the argument s is not the null string test -f file true if file exists test -r file true if file is readable test -w file true if file is writable test -d file true if file is a directory

Control flow - while


The actions of the for loop and the case branch are determined by data available to the shell. A while or until loop and an if then else branch are also provided whose actions are determined by the exit status returned by commands. A while loop has the general form
while command-list1 do command-list2 done

The value tested by the while command is the exit status of the last simple command following while. Each time round the loop command-list1 is executed; if a zero exit status is returned then commandlist2 is executed; otherwise, the loop terminates. For example,
while test $1 do ... shift done

is equivalent to
for i do ... done

shift is a shell command that renames the positional parameters $2, $3, ... as $1, $2, ... and loses $1.

Another kind of use for the while/until loop is to wait until some external event occurs and then run some commands. In an until loop the termination condition is reversed. For example,
until test -f file do sleep 300; done commands

will loop until file exists. Each time round the loop it waits for 5 minutes before trying again. (Presumably another process will eventually create the file.)

Control flow - if
Also available is a general conditional branch of the form,
if command-list then command-list else command-list fi

that tests the value returned by the last simple command following if.

The if command may be used in conjunction with the test command to test for the existence of a file as in
if test -f file then process file else do something else fi

An example of the use of if, case and for constructions is given in section 2.10.

A multiple test if command of the form


if ... then else ... if ... then ... else if ... ... fi fi

fi

may be written using an extension of the if notation as,


if ... then elif then ... ... ...

elif ... fi

...

The following example is the touch command which changes the `last modified' time for a list of files. The command may be used in conjunction with make (1) to force recompilation of a list of files.
flag= for i do case $i in -c) flag=N ;; *) if test -f $i then ln $i junk$$; rm junk$$ elif test $flag then echo file \'$i\' does not exist else >$i fi esac done

The -c flag is used in this command to force subsequent files to be created if they do not already exist. Otherwise, if the file does not exist, an error message is printed. The shell variable flag is set to some non-null string if the -c argument is encountered. The commands
ln ...; rm ...

make a link to the file and then remove it thus causing the last modified date to be updated.

The sequence
if command1 then command2 fi

may be written
command1 && command2

Conversely,
command1 || command2

executes command2 only if command1 fails. In each case the value returned is that of the last simple command executed.