Está en la página 1de 26

Experiment No.

1
Study and implementation of various commands: Ls, man, pwd, cd, cat, mkdir, chmod, cp, rm,
mv, wc, cmp, cal, who wild cards.
Apparatus required: Computer having UNIX O.S.
Theory: following is study and implementation of commands:-
1.ls Command:- This commands lists your files. There are various options associated with
options :-

ls :- list all the files in your home directory, this command has many options.
ls l:- list all the file names, permissions, group, etc in long format.
ls a:- list all the files including hidden files that start with . .
ls -lt :- list all files names based on the time of creation, newer files bring first.
ls F:- list files and directory names will be followed by slash.
ls R:-lists all the files and files in the all the directories, recursively.
This command will give you a list of all the names of your files. If you just got your account, you
won't see any names until you actually create some files.
Syntax: - %ls
Output: - groceries schedule todo
This is telling you that you have three files. In alphabetical order, their names are groceries,
schedule, and todo
2.Pwd Command:-This command tells the name of present working directory.
Syntax: - %pwd
Abc
It describe the name of present working directory i.e. Abc.
3.cd command --- change directory. You basically 'go' to another directory, and you will see the
files in that directory when you do 'ls'. You always start out in your 'home directory', and you can
get back there by typing 'cd' without arguments. 'cd ..' will get you one level up from your
current position. You don't have to walk along step by step - you can make big leaps or avoid
walking around by specifying pathnames.

At any given time, you are located in some current working directory within the Unix file tree.
When you log in, your current directory is set to your home directory.
You can change your current working directory any time by using the cd command (this stands
for "change directory"). For example, if the current directory has a subdirectory named details,
you can change to that directory using the command:

Syntax :- Cd directory name

Syntax: - %cd details

You can always find out the absolute pathname of the current working directory by typing the
command:

%pwd

Assuming you are using csh as your shell, you can always return to your home directory by
typing:

% cd~
4.mkdir command:- This command creates a new directory

You can create a directory by using the mkdir command. For example, to create a directory
named mayhem within the current working directory:
Syntax: - mkdir directory name
Example: - % mkdir mayhem

You may create a subdirectory within any directory where you have write permission. For
example, to create a directory called /u/trixie/bazz/fazz, assuming that directory /u/trixie/bazz
already exist:

Example: - % mkdir /u/trixie/bazz/fazz


5.Chmod Command: - this command is used to change the read, write, and execute permissions
on your files. The default is that only you can look at them and change them, but you may
sometimes want to change these permissions.
Syntax: - chmod options filename
For example, chmod o+r filename will make the file readable for everyone, and
chmod o-r filename will make it unreadable for others again. Note that for someone to be able
to actually look at the file the directories it is in need to be at least executable.

6.cp filename1 filename2 --- copies a file


If you want to make an exact copy of the contents of a file, figure out what you want to name the
copy, and then type the command.

Syntax: - cp oldname newname


Where oldname is the name of the existing file you want to copy. A new file will be created with
the name newname and the same contents as the original.

If I want to copy oldfile to other directory for example /tmp then


Example: - % cp oldfile /tmp/newfile

Useful options available with cp are -p and -r . -p options preserves the modification time and
permissions, -r recursively copy a directory and its files, duplicating the tree structure.

7.Rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for
confirmation before actually deleting anything. You can make this your default by making an
alias in your .cshrc file.
Once you have no more need for a disk file, you can get rid of it permanently by using the Unix
rm command.
Syntax: - rm filename
Note: - When you remove a file, it is gone forever. There is no easy way to get it back. Please be
careful that you do not remove a file that you really need.
To delete a file from your account, enter this command: Where filename identifies the file you
want to remove. You can remove more than one file at a time.
For example, this command
% rm oldbills oldnotes badjokes
This command will remove the three named files.
Options:
rm oldfile will delete file named oldfile.
rm -f option will remove write-protected files without prompting.
rm -r option will delete the entire directory as well as all the subdirectories, very
dangerous command.
8. wc Command: tells you how many lines, words, and characters there are in a file
wc - print the number of newlines, words, and bytes in files
Syntax: - wc [Option]... [File]...

Description:-Print newline, word, and byte counts for each FILE, and a total line if more than
one FILE is specified. With no FILE, or when FILE is -, read standard input.
-c, --bytes :-print the byte counts
-m, --chars :- print the character counts
-l, --lines :-print the newline counts
-L, --max-line-length: - print the length of the longest line
-w, --words :-print the word counts
--help :-display this help and exit
--version:- output version information and exit.

9. mv command:- This moves a file (i.e. gives it a different name, or moves it into a different
directory.

The Unix mv command can be used to change the name of a file:

Syntax: - % mv oldname newname

This will not affect the contents of the file. It will simply change its name from oldname to
newname.
Examples:
mv oldfile newfile will rename oldfile to newfile.
mv -i oldfile newfile for confirmation prompt.
mv -f oldfile newfile will force the rename even if target file exists.
mv * /usr/bajwa/ will move all the files in current directory to /usr/bajwa directory.
10. Who Command:- This command tells you who's logged on, and where they're coming from.
Useful if you're looking for someone who's actually physically in the same building as you,
or in some other particular location.
Syntax : who [OPTION]... [ FILE | ARG1 ARG2 ]

Options :-
-a, --all
same as -b -d --login -p -r -t -T -u
-b, --boot
time of last system boot
-d, --dead
print dead processes
-H, --heading
print line of column headings
-l, --login
print system login processes
--lookup
attempt to canonicalize hostnames via DNS
-m
only hostname and user associated with stdin
-p, --process
print active processes spawned by init
-q, --count
all login names and number of users logged on
-r, --runlevel
print current runlevel
-s, --short
print only name, line, and time (default)
-t, --time
print last system clock change
-T, -w, --mesg
add user's message status as +, - or ?
-u, --users
list users logged in
--message
same as -T
--writable
same as -T
--help
display this help and exit
--version
output version information and exit

If FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common. If ARG1 ARG2
given, -m presumed: `am i' or `mom likes' are usual.
11. File Command:-
File command displays about the contents of a given file, whether it is a text (Ascii) or binary
file. To use it type
Syntax: - file filename
For example I have cal.txt which has ascii characters about calander of current month and I have
resume1.doc file which is a binariy file in microsoft word. I will get
Example: - file resume.doc
resume1.doc: data
file cal.txt
cal.txt: ascii text
12. Man Command:- This command format and display the on-line manual pages.
Syntax: man [-acdfFhkKtwW] [--path] [-m system] [-p string] [-C config_file] [-M pathlist] [-
P pager] [-B browser] [-H htmlpager] [-S section_list] [section] name ...

Description:-If you specify section, man only looks in that section of the manual. name is
normally the name of the manual page, which is typically the name of a command, function, or
file. However, if name contains a slash (/) then man interprets it as a file specification, so that
you can do man ./foo.5 or even man /cd/foo/bar.1.gz.
OPTIONS
-C config_file:- Specify the configuration file to use; the default is /etc/man.config.
-M path:-Specify the list of directories to search for man pages. Separate the directories with
colons. An empty list is the same as not specifying -M at all.
-P pager: - Specify which pager to use. This option overrides the MANPAGER environment
variable, which in turn overrides the PAGER variable. By default, man uses /usr/bin/less -is.
-B: -Specify which browser to use on HTML files. This option overrides the BROWSER
environment variable. By default, man uses /usr/bin/less-is,
-H :-Specify a command that renders HTML files as text. This option overrides the
HTMLPAGER environment variable. By default, man uses /bin/cat,
-S section_list :-List is a colon separated list of manual sections to search. This option overrides
the MANSECT environment variable.
-a :-By default, man will exit after displaying the first manual page it finds. Using this option
forces man to display all the manual pages that match name, not just the first.
-c :-Reformat the source man page, even when an up-to-date cat page exists. This can be
meaningful if the cat page was formatted for a screen with a different number of columns, or if
the preformatted page is corrupted.
-d :-Don't actually display the man pages, but do print gobs of debugging information.
-D :-Both display and print debugging info.
-f :-Equivalent to whatis.
-F or --preformat :-Format only - do not display.
-h :-Print a help message and exit.
-k :-Equivalent to apropos.
-K :-Search for the specified string in *all* man pages. Warning: this is probably very slow! It
helps to specify a section.
-m system :-Specify an alternate set of man pages to search based on the system name given.
-p string :-Specify the sequence of preprocessors to run before nroff or troff. Not all
installations will have a full set of preprocessors. Some of the preprocessors and the letters used
to designate them are: eqn (e), grap (g), pic (p), tbl (t), vgrind (v), refer (r). This option overrides
the MANROFFSEQ environment variable.
-t :-Use /usr/bin/groff -Tps -mandoc to format the manual page, passing the output to stdout.
The default output format of /usr/bin/groff -Tps -mandoc is Postscript, refer to the manual page
of /usr/bin/groff -Tps -mandoc for ways to pick an alternate format.

Depending on the selected format and the availability of printing devices, the output may need to
be passed through some filter or another before being printed.
-w or --path :-Don't actually display the man pages, but do print the location(s) of the files that
would be formatted or displayed. If no argument is given: display (on stdout) the list of
directories that is searched by man for man pages. If manpath is a link to man, then "manpath"
is equivalent to "man --path".
-W:-Like -w, but print file names one per line, without additional information. This is useful in
shell commands like man -aW man | xargs ls -l
13. Rmdir command: - rmdir command will remove directory or directories if a directory is
empty.
Options:

rm -r directory_name will remove all files even if directory is not empty.


rmdir sandeep is how you use it to remove sandeep directory.
rmdir -p :-will remove directories and any parent directories that are empty.
rmdir -s :-will suppress standard error messages caused by -p.

14. Cat :
cat cal.txt
Cat command displays the contents of a file here cal.txt on screen (or standard out).
15. Cmp:

cmp command compares the two files. For exmaple I have two different files fileone and filetwo.
Syntax: - cmp fileone filetwo
fileone filetwo differ: char 80, line 4

If I run cmp command on similar files nothing is returned.


-s command can be used to return exit codes. i.e. return 0 if files are identical, 1 if files are
different, 2 if files are inaccessible.
This following command prints a message 'no changes' if files are same
cmp -s fileone file1 && echo 'no changes' .
no changes

16. Cal: cal command will print the calander on current month by default. If you want to print
calander of august of 1965. That's eightht month of 1965.
Example: - cal 8 1965 will print following results.
August 1965
S M Tu W Th F S
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Experiment No. 2 :- Implementation of shell programming with various control statements and
loops.
Apparatus: - Computer having UNIX O.S.
Theory :-
Shell programming concepts and commands:-
Shell programming is integral part of UNIX operating systems. Shell is command line
userinterface to Unix operating system, User have an option of picking an interface on Unix such
as ksh, csh, or default sh., these are called shells (interface). Shell programming is used to
automate many tasks. Shell programming is not a programming language in the truest sense of
word since it is not compiled but rather an interpreted language. UNIX was written in C
language and thus c language is integral part of UNIX and available on all versions. Shells, like
ksh and csh are popular shells on Unix although there are 5 or 6 different shells available but I
will only be discussing ksh and csh as well as sh. Common features among all shells are job
control, for example if I am running a processes which is searching the whole system for .Z files
and output is directed to a file named compressed files.
Example:

find / -name *.Z -print > compressedfiles


then after entering this command hitting
<control z>
key will suspend this job, then entering
bg
at command line will put this job in background, entering
fg
will put this job in foreground. Entering
jobs
at command line will show me all my concurrent jobs that are running.

Other common features

o > will redirect output from standard out (screen) to file or printer or whatever you
like.
o >> filename will append at the end of a file called filename.
o < will redirect input to a process or commnand.
o | pipe output, or redirect output, good for joining commands, i.e. find command
with cpio, etc.
o & at the end of command will run command in background.
o ; will separate commands on same line.
o * will match any characters in a file or directories. junk* will match all files with
first 4 letters
o ? will match single characters in a file.
o [] will match any characters enclosed.
o () execute in subshell.
o ` ` to run a command inside another command and use its output.
o " " partial quote for variables.
o ' ' full quote for variables.
o # begin comment (if #/bin/ksh or csh or sh is entered at first line of script it runs
script in that shell)
o bg background execution.
o break break from loop statements.
o continue Resume a program loop.
o Kill pid number will terminate running jobs
o stop will stop background job.
o suspend will suspend foreground job.
o wait will wait for a background job to finish.
1. Bourne Shell (sh shell).
sh or Bourne shell is default shell of Unix operating systems and is the most simplest
shell in Unix systems.
Examples:

cd; ls execute one after another.


(date;who;pwd)> logifile will redirect all the output from three commands to a
filenamed logfile.
sort file | lp will first sort a file and then print it.
alias [options] [name[='command']] will let you create your own commands. i.e.
o alias ll="ls -la" will execute `ls -la` command whenever ll is entered.
let expressions is syntax of let statement.
o let i=i+1 will work as a counter with i incrementing each time this statement is
encountered.
for x[in list] do commands done is syntax for for do loop.
function name {commands;} is the syntax of a function which can be called from
anywhere in program.
if condition1 then commands1 elif condition2 then commands2 ... ... ... else commands3
fi

2. Ksh shell (Korn).


Ksh or Korn shell is widely used shell.
3. Csh or C shell
csh is second most used shell.
Shell Programming:-
Comments
The "pound" or "hash" sign (#) signals the start of a comment. This sign and anything that
follows it up to the end of the line is interpreted as a comment for the author and is not
executed.
Commands to be executed in a new process
If a line in the script does not begin with one of the reserved keywords that is used for variable
operations or flow-control, it is assumed to be a command that you want to execute as a new
child process. The entire line is scanned, looking for variables that need to be substituted and
wildcards characters ("*", "?", etc) that need to be matched to filenames. After all substitutions
are performed, it is executed as if you had typed it at the terminal.
Setting and substituting variable values
Special keywords such as set or the $ symbol indicate a variable is to be set or used.
Flow-of-control: loops, conditionals
Special keywords such as if or foreach are used to start lines in the script that provide flow
control or conditional execution.
How do you execute (run) a shell script?

There are two methods you can use to execute a shell script.

First, you can give the script file name as an argument to an instance of the shell program, that is,
type a command like:
csh filename
csh is the name of the C-shell program itself. This command starts up a new C-shell process that
executes the commands in the script filename and then terminates.

Second, you can give the name of the shell script itself as a command, just like any other
program on Unix. First, you have to let the Unix kernel recognize that this is a shell script by
doing the following two steps. Then you can simply type the shell's filename as a command
name to execute it. The kernel will automatically start up a new C-shell process to execute the
commands in the script.

Note that your login shell has to be able to find the shell script file when you type its name as a
command. The login shell only looks in a set of specific directories, called its path, to find files
that contain programs. On pangea, the default path includes your current working directory, so
you can run a shell script in the current directory simply by typing its name. Otherwise, type the
absolute pathname of the script (for example, /home/sysop/farrell/programs/addup), or add the
directory where the script lives to your standard path. Whenever you add a directory to your
standard path, you must run the rehash built-in C-shell command to tell your login shell to
rebuild its list of programs using your new path definition.
To make your shell script file executable as a program, do these steps:

Put the following line as the first line in your script:


#! /bin/csh -f
This is a special comment telling the kernel that you want this script to be executed by the C-
shell (there is an alternate shell named simply sh). The -f option helps the command to start up
faster by skipping the initial read of the .cshrc file.

Use chmod to set execute permission for your file. For instance, if you want anyone to be able to
execute the script file, use
chmod ugo+x filename
Flow of control Statements:-

if and foreach are the basic flow-of-control statements. There are more advanced ones named
switch and while which are similar to the statements of the same name in the C language.
1.if :- The if command allows you to conditionally execute a command or set of commands
depending upon whether some expression is true. There are two forms.
if ( logical_expression ) command ...
This form will execute command (which can have a long list of arguments) if the
logical__expression is true. This expression can be one of the logical or file testing
expressions described above. For example, you can test if a file whose name is stored in
the shell's built-in variable $1 (first argument to the shell script) exists as a plain file, and if
so, make a backup copy of it with:

if ( -f $1 ) cp $1 $1.bak

This simple cp command will not work if given a directory to copy, which is why there is
the test for a "plain" file.

Syntax of if expression:-
if ( logical_expression ) then
block of commands - any number of lines
to be executed if logical_expression is "true"
(or has non-zero value).
else

another block of commands - any number of lines


to be executed if logical_expression is "false"
(or has value 0).
endif

This form allows you to execute more than one command if the expression is true. The then
keyword must follow the logical_expression test on the same line, and the endif keyword
must be on a line by itself to end the entire if command.

The else statement is optional. If you use this, the else keyword must be on a line by itself.
The following lines up to the endif are executed if the expression was false.

The "blocks of commands" may in turn contain additional nested if commands. Just be sure
that each if has a matching endif statement enclosed in the same block.

Example of if statement:-
if [ 1 -le 0 ]
then
echo YES
else
echo NO
fi

Output:- NO

Example No. 2 :-
rank=captain
if [ "$rank" = colonel ]
then
echo Hannibal Smith
elif [ "$rank" = captain ]
then
echo Howling Mad Murdock
elif [ "$rank" = lieutenant ]
then
echo Templeton Peck
else
echo B.A. Baracus
fi
Output:- Howling Mad Murdock
2.foreach :- This statement allows you to execute a loop, like a do statement in Fortran or a for
statement in C.

The syntax is:

foreach name (wordlist)

block of statements to be executed


end

foreach and end are keywords. The end statement must be on a line by itself.

name is the name of a variable that you create. This is the "loop index".

(wordlist) is a list of "words", meaning any character strings separated by blanks. The
parentheses are required. The "word list" can be a list of actual constant values, or the results of
variable substitution, arithmetic expressions, or command substitution.

When the foreach statement is encountered in a shell script, the wordlist is evaluated (necessary
variable and command substitutions and expressions are done) and stored. Then the new variable
name is set equal to the first word in the list and the block of statements is executed. When the
end statement is reached, the script goes back to the foreach line and sets the variable name equal
to the next word in the list and executes the block of statements again. This is done over and over
until all words in the wordlist have been used up.

This type of looping statement is good for repetitively executing the same commands for a set of
arguments. For example, you could check all the arguments given to the shell to see if they are
plain files, and if so, make backup copies, using these statements in a shell script:

foreach file ( $* )
if (-f $file) cp $file $file.bak
end

The foreach command can also be used interactively from the terminal. In this form, you will get
question mark prompts (?) to enter your commands. When done, type end after one of these
prompts. For example, you could type the following commands interactively at your terminal to
make backup copies of all Fortran programs in your current directory:

foreach file ( *.f )


? if (-f $file) cp $file $file.bak
? end

Conditional execution

Okay, so now we know how to evaluate some conditions. Let's see how make use of this ability
to do some programming.

All programming languages need two things: a form of decision making or conditional execution
and a form of repetition or looping. We'll get to looping later, for now let's concentrate on
conditional execution. Bourne Shell supports two forms of conditional execution, the if-
statement and the case-statement.

3.Case Statement:-
The case-statement is sort of a special form of the if-statement, specialized in the kind of test
demonstrated in the last example: taking a value and comparing it to a fixed set of expected
values or patterns. The case statement is used very frequently to evaluate command line
arguments to scripts. For example, if you write a script that uses switches to identify command
line arguments, you know that there are only a limited number of legal switches. The case-
statement is an elegant alternative to a potentially messy if-statement in such a case.

The general form of the case statement is


Case value in
Patteren0) command-list-0;;
Patteren1) command-list-1;;
.
esac

The value can be any value, including an environment variable. Each pattern is a regular
expression and the command list executed is the one for the first pattern that matches the value
(so make sure you don't have overlapping patterns). Each command list must end with a double
semicolon. The return status is zero if the statement terminates without syntax errors.

Example of Case Statement:-


rank=captain
case $rank in
colonel) echo Hannibal Smith;;
captain) echo Howling Mad Murdock;;
lieutenant) echo Templeton Peck;;
sergeant) echo B.A. Baracus;;
*) echo OOPS;;
Esac
Output:-
Howling Mad Murdock

Difference between if and case statement:-

The technical difference is this: the case-statement works off of data available to the shell (like
an environment variable), whereas the if-statement works off the exit status of a program or
command. Since fixed values and environment variables depend on the shell but the exit status is
a concept general to the Unix system, this means that the if-statement is more general than the
case-statement.
Let's look at a slightly larger example, just to put the two together and compare:
#!/bin/sh
if [ "$2" ]
then
sentence="$1 is a"
else
echo Not enough command line arguments! >&2
exit 1
fi
case $2 in
fruit|veg*) sentence="$sentence vegetarian!";;
meat) sentence="$sentence meat eater!";;
*) sentence="${sentence}n omnivore!";;
esac
echo $sentence

Note that this is a shell script and that it uses positional variables to capture command-line
arguments. The script starts with an if-statement to check that we have the right number of
arguments note the use of 'test' to see if the value of variable $2 is not null and the exit status of
'test' to determine how the if-statement proceeds. If there are enough arguments, we assume the
first argument is a name and start building the sentence that is the result of our script. Otherwise
we write an error message (to stderr, the place to write errors; read all about it in Files and
streams) and exit the script with a non-zero return value. Note that this else statement has a
command list with more than one command in it.

Assuming we got through the if-statement without trouble, we get to the case-statement. Here we
check the value of variable $2, which should be a food preference. If that value is either fruit or
something starting with veg, we add a claim to the script result that some person is a vegetarian.
If the value was exactly meat, the person is a meat eater. Anything else, he is an omnivore. Note
that in that last case pattern clause we have to use curly braces in the variable substitution; that's
because we want to add a letter n directly onto the existing value of sentence, without a space in
between.

Loop Statement:-

In addition to conditional execution mechanisms every programming language needs a means of


repetition, repeated execution of a set of commands. The Bourne Shell has several mechanisms
for exactly that: the while-statement, the until-statement and the for-statement.

1.The while loop

The while-statement is the simplest and most straightforward form of repetition statement in
Bourne shell. It is also the most general. Its general form is this:

Syntax :-
While command-list1
Do command-list2
done

The while-statement is interpreted as follows:

1. Execute the commands in command list 1.


2. If the exit status of the last command is non-zero, the statement terminates.
3. Otherwise execute the commands in command list 2 and go back to step 1.
4. If the statement does not contain a syntax error and it ever terminates, it terminates with
exit status zero.

Much like the if-statement, you can use a full command list to control the while-statement and
only the last command in that list actually controls the statement. But in reality you will probably
want to limit yourself to one command and, as with the if-statement, you will usually use the
'test' program for that command.
A while loop that prints all the values between 0 and 10
Code:
counter=0

while [ $counter -lt 10 ]


do
echo $counter
counter=`expr $counter + 1`
done

Output:
0
1
2
3
4
5
6
7
8
9
Note the use of command substitution to increase the value of the counter variable.

The while-statement is commonly used to deal with situations where a script can have an
indeterminate number of command-line arguments, by using the shift command and the special
'$#' variable that indicates the number of command-line arguments:
Printing all the command-line arguments
#!/bin/sh

while [ $# -gt 0 ]
do
echo $1
shift
done

[edit] The until loop

The until-statement is also a repetition statement, but it is sort of the semantic opposite of the
while-statement. The general form of the until-statement is

until command-list1
do command-list2
done

The interpretation of this statement is almost the same as that of the while-statement. The only
difference is that the commands in command list 2 are executed as long as the last command of
command list 1 returns a non-zero status. Or, to put it more simply: command list 2 is executed
as long as the condition of the loop is not met.

Whereas while-statements are mostly used to establish some effect ("repeat until done"), until-
statements are more commonly used to poll for the existence of some condition or to wait until
some condition is met. For instance, assume some process is running that will write 10000 lines
to a certain file. The following until-statement waits for the file to have grown to 10000 lines:
Code for Waiting for myfile.txt to grow to 10000lines
until [ $lines -eq 10000 ]
do
lines=`wc -l dates | awk '{print $1}'`
sleep 5
done
The for loop:-

In the section on Control flow, we discussed that the difference between if and case was that the
first depended on command exit statuses whereas the second was closely linked to data available
in the shell. That kind of pairing also exists for repetition statements: while and until use
command exit statuses and for uses data explicitly available in the shell.

The for-statement loops over a fixed, finite set of values. Its general form is
for name in w1,w2
do command-list
done
This statement executes the command list for each value named after the 'in'. Within the
command list, the "current" value wi is available through the variable name. The value list must
be separated from the 'do' by a semicolon or a newline. And the command list must be separated
from the 'done' by a semicolon or a newline. So, for example:
Program: - A for loop that print some values for myval in Abel Bertha Charlie Delta Easy
Fox Gumbo Henry India
do
echo $myval Company
done
Output
Abel Company
Bertha Company
Charlie Company
Delta Company
Easy Company
Fox Company
Gumbo Company
Henry Company
India Company
The for statement is used a lot to loop over command line arguments. For that reason the shell
even has a shorthand notation for this use: if you leave off the 'in' and the values part, the
command assumes $* as the list of values. For example:

Using for to loop over command line arguments:-

Code:
#!/bin/sh
for arg
do
echo $arg
done
Output:-
$ sh loop_args.sh A B C D

A
B
C
D

3.While Loop:- Each while loop consists of a set of commands and a condition. The general sy

Syntax as follows for bash while loop:


while [ condition ]
do
command1
command2
commandN
done

1. The condition is evaluated, and if the condition is true, the command1,2N is executed.
2. This repeats until the condition becomes false.
3. The condition can be integer ($i < 5), file test ( -e /tmp/lock ) or string ( $ans != "" )

ksh while loop syntax:


while [[ condition ]] ; do
command1
command1
commandN
done

csh while loop syntax:


while ( condition )
commands
end

BASH while Loop Example


#!/bin/bash
c=1
while [ $c -le 5 ]
do
echo "Welcone $c times"
(( c++ ))
done

KSH while loop Example


#!/bin/ksh
c=1
while [[ $c -le 5 ]]; do
echo "Welcome $c times"
(( c++ ))
done
CSH while loop Example
#!/bin/csh
c=1
while ( $c <= 5 )
echo "Welcome $c times"
@ c = $c + 1
end

Another example:
#!/bin/csh
set yname="foo"
while ( $yname != "" )
echo -n "Enter your name : "
set yname = $<
if ( $yname != "" ) then
echo "Hi, $yname"
endif
end

También podría gustarte