Pages

Saturday, 21 April 2012

LINUX CLASS NOTES


Easy Shell Scripting

Introduction

Shell scripting can be defined as a group of commands executed in sequence. Let's start by describing the steps needed to write and execute a shell script:
Step 1: Open the file using an editor (e.g., "vi" or "pico".)
vi Firstshellscript.sh
Step 2: All shell scripts should begin with "#!/bin/bash" or whatever other shell you prefer. This line is called the shebang, and although it looks like a comment, it's not: it notifies the shell of the interpreter to be used for the script. The provided path must be an absolute one (you can't just use "bash", for example), and the shebang must be located on the first line of the script without any preceding space.
Step 3: Write the code that you want to develop. Our first shell script will be the usual "Hello World" routine, which we'll place in a file called 'Firstshellscript.sh'.
#!/bin/sh
echo "Hello World"
Step 4:The next step is to make the script executable by using the "chmod" command.
chmod 744 Firstshellscript.sh
or
chmod +x Firstshellscript.sh
Step 5: Execute the script. This can be done by entering the name of the script on the command line, preceded by its path. If it's in the current directory, this is very simple:
bash$ ./Firstshellscript.sh
Hello World
If you want to see the execution step-by-step - which is very useful for troubleshooting - then execute it with the '-x' ('expand arguments') option:
sh -x Firstshellscript.sh
+ echo 'Hello World'
Hello World
Category: Shell scripting
Shell scripting can be defined as a group of commands executed in sequence.
To see the contents of a script, you can use the 'cat' command or simply open the script in any text editor:
bash$ cat Firstshellscript.sh
#!/bin/sh
echo Hello World

 

Comments in a Shell

In shell scripting, all lines beginning with # are comments.
# This is a comment line.
# This is another comment line.
You can also have comments that span multiple lines by using a colon and single quotes:
: 'This is a comment line.
 
Again, this is a comment line.
 
My God, this is yet another comment line.'
Note: This will not work if there is a single quote mark within the quoted contents.

 

Variables

As you may or may not know, variables are the most significant part of any programming language, be it Perl, C, or shell scripting. In the shell, variables are classified as either system variables or user-defined variables.

System Variables

System variables are defined and kept in the environment of the parent shell (the shell from which your script is launched.) They are also called environment variables. These variable names consist of capital letters, and can be seen by executing the 'set' command. Examples of system variables are PWD, HOME, USER, etc. The values of these system variables can be displayed individually by "echo"ing the system variables. E.g., echo $HOMEwill display the value stored in the system variable HOME.
When setting a system variable, be sure to use the "export" command to make it available to the child shells(any shells that are spawned from the current one, including scripts):
bash$ SCRIPT_PATH=/home/blessen/shellscript
bash$ export SCRIPT_PATH
Modern shells also allow doing all this in one pass:
bash$ export SCRIPT_PATH=/home/blessen/shellscript

 

User-Defined Variables

These are the variables that are normally used in scripting - ones that you don't want or need to make available to other programs. Their names cannot start with numbers, and are written using lower case letters and underscores by convention - e.g. 'define_tempval'.
When we assign a value to a variable, we write the variable name followed by '=' which is immediately followed by the value, e.g., define_tempval=blessen(note that there must not be any spaces around the equals sign.) Now, to use or display the value in define_tempval, we have to use the echocommand and precede the variable name with a '$' sign, i.e.:
bash$ echo $define_tempval 
blessen
The following script sets a variable named "username" and displays its content when executed.
#!/bin/sh
 
username=blessen
echo "The username is $username"

 

Commandline Arguments

These are variables that contain the arguments to a script when it is run. These variables are accessed using $1, $2, ... $n, where $1 is the first command-line argument, $2 the second, etc. Arguments are delimited by spaces. $0 is the name of the script. The variable $# will display the number of command-line arguments supplied; this number is limited to 9 arguments in the older shells, and is practically unlimited in the modern ones.
Consider a script that will take two command-line arguments and display them. We'll call it 'commandline.sh':
#!/bin/sh
 
echo "The first variable is $1"
echo "The second variable is $2"
When I execute 'commandline.sh' with command-line arguments like "blessen" and "lijoe", the output looks like this:
bash$ ./commandline.sh blessen lijoe
The first variable is blessen
The second variable is lijoe

 

Exit status variable

This variable tells us if the last command executed was successful or not. It is represented by $?. A value of 0 means that the command was successful. Any other number means that the command was unsuccessful (although a few programs such as 'mail' use a non-zero return to indicate status rather than failure.) Thus, it is very useful in scripting.
To test this, create a file named "test", by running touch test. Then, "display" the content of the file:
bash$ cat test
Then, check the value of $?.
bash$ echo $?
0
The value is zero because the command was successful. Now try running 'cat' on a file that isn't there:
bash$ cat xyz1
bash$ echo $?
1
The value 1 shows that the above command was unsuccessful.

 

Scope of a Variable

I am sure most programmers have learned (and probably worked with) variables and the concept of scope (that is, a definition of where a variable has meaning.) In shell programming, we also use the scope of a variable for various programming tasks - although this is very rarely necessary, it can be a useful tool. In the shell, there are two types of scope: global and local. Local variables are defined by using a "local" tag preceding the variable name when it is defined; all other variables, except for those associated with function arguments, are global, and thus accessible from anywhere within the script. The script below demonstrates the differing scopes of a local variable and a global one:
#!/bin/sh
 
display()
{
    local local_var=100
    global_var=blessen
    echo "local variable is $local_var"
    echo "global variable is $global_var"
}
 
echo "======================"
display
echo "=======outside ========"
echo "local variable outside function is $local_var"
echo "global variable outside function is $global_var"
Running the above produces the following output:
======================
local variable is 100
global variable is blessen
=======outside ========
local variable outside function is 
global variable outside function is blessen
Note the absence of any value for the local variable outside the function.

 

Input and Output in Shell Scripting

For accepting input from the keyboard, we use read. This command will read values typed from the keyboard, and assign each to the variable specified for it.
read <variable_name>
For output, we use the echo command.
echo "statement to be displayed"

 

Arithmetic Operations in Shell Scripting

Like other scripting languages, shell scripting also allows us to use arithmetic operations such as addition, subtraction, multiplication, and division. To use these, one uses a function called expr; e.g., "expr a + b" means 'add a and b'.
e.g.:
sum=`expr 12 + 20`
Similar syntax can be used for subtraction, division, and multiplication. There is another way to handle arithmetic operations; enclose the variables and the equation inside a square-bracket expression starting with a "$" sign. The syntax is
$[expression operation statement]
e.g.:
echo $[12 + 10]
[ Note that this syntax is not universal; e.g., it will fail in the Korn shell. The '$((...))' syntax is more shell-agnostic; better yet, on the general principle of "let the shell do what it does best and leave the rest to the standard toolkit", use a calculator program such as 'bc' or 'dc' and command substitution. Also, note that shell arithmetic is integer-only, while the above two methods have no such problem. -- Ben ]

 

Conditional Statements

Let's have some fun with a conditional statement like "if condition". Most of the time, we shell programmers have situations where we have to compare two variables, and then execute certain statements depending on the truth or falsity of the condition. So, in such cases, we have to use an "if" statement. The syntax is show below:
if [ conditional statement ]
then
        ... Any commands/statements ...
fi
The script cited below will prompt for a username, and if the user name is "blessen", will display a message showing that I have successfully logged in. Otherwise it will display the message "wrong username".
#!/bin/sh
 
echo "Enter your username:"
read username
 
if [ "$username" = "blessen" ]
then
        echo 'Success!!! You are now logged in.'
else
        echo 'Sorry, wrong username.'
fi
Remember to always enclose the variable being tested in double quotes; not doing so will cause your script to fail due to incorrect syntax when the variable is empty. Also, the square brackets (which are an alias for the 'test' command) must have a space following the opening bracket and preceding the closing one.

 

Variable Comparison

In shell scripting we can perform variable comparison. If the values of variables to be compared are numerical, then you have to use these options:
-eq Equal to
-ne Not Equal to
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater then or equal to
If they are strings, then you have to use these options:
= Equal to
!= Not Equal to
< First string sorts before second
> First string sorts after second

 

Loops

The "for" Loop

The most commonly used loop is the "for" loop. In shell scripting, there are two types: one that is similar to C's "for" loop, and an iterator (list processing) loop.
Syntax for the first type of "for" loop (again, this type is only available in modern shells):
for ((initialization; condition; increment/decrement))
do
        ...statements...
done

Example:
#!/bin/sh
 
for (( i=1; $i <= 10; i++ ))
do
        echo $i
done
This will produce a list of numbers from 1 to 10. The syntax for the second, more widely-available, type of "for" loop is:
for <variable> in <list>
do
        ...statements...
done
This script will read the contents of '/etc/group' and display each line, one at a time:
#!/bin/sh
 
count=0
for i in `cat /etc/group`
do
        count=`expr "$count" + 1`
        echo "Line $count is being displayed"
        echo $i
done
 
echo "End of file"
Another example of the "for" loop uses "seq" to generate a sequence:
#!/bin/sh
 
for i in `seq 1 5`
do
        echo $i
done

 

While Loop

The "while" loop is another useful loop used in all programming languages; it will continue to execute until the condition specified becomes false.
while [ condition ]
do
        ...statement...
done
The following script assigns the value "1" to the variable numand adds one to the value of numeach time it goes around the loop, as long as the value of num is less than 5.
#!/bin/sh
 
num=1
 
while [$num -lt 5]; do num=$[$num + 1]; echo $num; done
Category: Programming
[Break] code into small chunks called functions, and call them by name in the main program. This approach helps in debugging, code re-usability, etc.

Select and Case Statement

Similar to the "switch/case" construct in C programming, the combination of "select" and "case" provides shell programmers with the same features. The "select" statement is not part of the "case" statement, but I've put the two of them together to illustrate how both can be used in programming.
Syntax of select:
select <variable> in <list>
do
        ...statements...
done
Syntax of case:
case $<variable> in
        <option1>) statements ;;
        <option2>) statements ;;
        *) echo "Sorry, wrong option" ;;
esac
The example below will explain the usage of select and case together, and display options involving a machine's services needing to be restarted. When the user selects a particular option, the script starts the corresponding service.
#!/bin/bash
 
echo "***********************"
select opt in apache named sendmail
        do
        case $opt in
               apache)        /etc/rc.d/init.d/httpd restart;;
               named)         /etc/rc.d/init.d/named restart;;
               sendmail)      /etc/rc.d/init.d/sendmail restart;;
               *)                     echo "Nothing will be restarted"
        esac
        echo "***********************"
 
        # If this break is not here, then we won't get a shell prompt.
        break
 
done
[ Rather than using an explicit 'break' statement - which is not useful if you want to execute more than one of the presented options - it is much better to include 'Quit' as the last option in the select list, along with a matching case statement. -- Ben ]

 

Functions

In the modern world where all programmers use the OOP model for programming, even we shell programmers aren't far behind. We too can break our code into small chunks called functions, and call them by name in the main program. This approach helps in debugging, code re-usability, etc.
Syntax for "function" is:
<name of function> ()
{       # start of function
        statements
}       # end of function
Functions are invoked by citing their names in the main program, optionally followed by arguments. For example:
#!/bin/sh
 
sumcalc ()
{
        sum=$[$1 + $2]
}
 
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
 
sumcalc $num1 $num2
 
echo "Output from function sumcalc: $sum"

 

Debugging Shell Scripts

Now and then, we need to debug our programs. To do so, we use the '-x' and '-v' options of the shell. The '-v' option produces verbose output. The '-x' option will expand each simple command, "for" command, "case" command, "select" command, or arithmetic "for" command, displaying the expanded value of PS4, followed by the command and its expanded arguments or associated word list. Try them in that order - they can be very helpful when you can't figure out the location of a problem in your script.

Installing linux

Installing linux

64 MB of memory and 4 GB of hard drive and a slow CPU -- in this day and age, anyhow: AMD-K6 475 -- it hasn't seen much use of late.

Preparations for Installation

Category: Security
Blindfolded by people who (maybe) think they are helping to make passwords secure, I am normally forced to use very weak passwords to ensure the ability to enter them correctly again. Believe me, if you can touch-type, you can re-enter the same sequence twice and not know what it was!
Since this machine had been in use at one time, the partitioning was irrelevant and so it was time to re-partition. And because it has far too little memory for current software, I gave it a swap partition of 256 MB. The remainder of the 4 GB was available for Knoppix. All this, of course, happened after a successful boot from the Knoppix 5.0 CD.
By the way, if the combination of main memory and disk storage is not adequate, Knoppix complains at length, sounding as if booting will fail. Same thing booting from the CD with the parameter NOSWAP.
But Knoppix boots fine -- it just doesn't boot into KDE. It announces TWM, which reminds me of FVWM (I think) -- as in "focus follows cursor" -- and I don't know when last I saw that! Perfectly usable, if you are comfortable with the command line.
Also, don't just allocate a partition for swap and expect it to be used. It must have partition ID 82 and, equally important, must have been initialized by something like: /sbin/mkswap /dev/hda1.

Installation

After that, installation was pretty much a piece of cake, other than a couple of problems discussed below. First, boot Knoppix from CD or DVD and start the installation process with "sudo knoppix-installer". All the pretty pictures aren't really justified, but just to make clear how straight-forward the process is, here they are:
After the introductory screen we select 'Install' since we haven't yet had Knoppix on this machine.
But before starting the installation, there might be a decision or two needed:

Initially I had tried to choose 'Knoppix' since I knew it from CD - but ran into problems. Debian worked fine, despite being the so-called "unstable" version.
Other than the swap partition there wasn't much choice.
I really wanted ext2 but that not being an option we (temporarily) live with ext3.
Your full name is, of course, up to you.
As is, ahh, your user name...
...and password.
Note the option not to hide the password as you enter it. In my book that is a sign of professionalism. This is quality software. Leave it up to me to decide whether it is safe to show what I am typing. No one can know in advance whether I am in a place where it is safe for me to look at the password as I enter it. Blindfolded by people who (maybe) think they are helping to make passwords secure, I am normally forced to use very weak passwords to ensure the ability to enter them correctly again. Believe me, if you can touch-type, you can re-enter the same sequence twice and not know what it was!
Now, we choose the root password...
...and the host name.
No need to worry about whether to tromp on the MBR - we're overwriting the entire thing, Master Boot Record included.
OK - we have now reached the critical point! Take a deep breath, and start the installation.
Yes, do save the configuration (otherwise, Knoppix bails out.)
Here is one last chance to review things.
And now a couple of informative windows to which no response was needed (I did reject creation of a boot floppy at one point).


There were many more such informative windows but that essentially was the entire installation. Pretty tame, right?

Problems

By today's standards this machine with 64 MB is so short of memory that almost no current OS could run on it. Even Knoppix can't, without help. Giving it a large (factor of 4) swap partition makes it possible for the system to install and function. But this has consequences that make doing it a judgement call: slow may be better than dead in the water, but how useful is it?
For example, OpenOffice is barely marginally useful. I used it to start this article because it gave me an HTML framework. Unlikely that I could have used it beyond that because of the "swapping" -- from hard drive to memory, which isn't there -- and thus to swap, which is on the hard drive...
And I wasn't particularly happy with the file system options. At least on this old hardware, which is never going to be run as a multi-user system, there is absolutely no need for journaling (besides, ":!sync" is powerful enough for me). So I turned it off. That, however, required adjusting the entry in /etc/fstab as well.
root@1[knoppix]# tune2fs -o ^has_journal /dev/hda2
tune2fs 1.39-wip (09-apr-2006)
root@1[knoppix]# mount /dev/hda2 /mnt
root@1[knoppix]# vi /mnt/etc/fstab
root@1[knoppix]# head /mnt/etc/fstab
# /etc/fstab: filesystem table.
#
# filesystem  mountpoint  type  options  dump  pass
#/dev/hda2  /  ext3  defaults,errors=remount-ro  0  1
/dev/hda2  /  ext2  defaults,errors=remount-ro  0  1         <<=== here 
 
proc  /proc  proc  defaults  0  0
/dev/fd0  /floppy  vfat  defaults,user,noauto,showexec,umask=022  0  0
usbfs  /proc/bus/usb  usbfs  devmode=0666  0  0
sysfs  /sys  sysfs  defaults  0  0
root@1[knoppix]# 
On boot, there were problems with lost IRQs. I tried several other boot parameters but they made no difference. In any case, it didn't matter: the default boot paragraph in the Grub configuration file is perfectly functional.
Some versions of Linux mount external devices automatically. This is not the case with Knoppix. I like to do "tail /etc/fstab" to find out what has just been made available and then mount whatever it is. Alternatively, you can just wait for hotplug to open a window asking about it and let it mount the device.
But the entries in /etc/fstab are not always appropriate. For example, if the entry for /floppy includes vfat, it may be necessary to mount it as "mount -t ext2 /dev/fd0 /floppy".
I also had considerable trouble with the UID/GID inserted into /etc/fstab by Knoppix on hotplug. Since there is no user or group "knoppix", I had to remove them to be able to mount as other than root:
web@lohgoamd:~$ tail -3 /etc/fstab
/dev/hda1 /media/hda1 auto noauto,users,exec 0 0
# added by knoppix
/dev/sda1 /media/sda1 vfat noauto,users,exec,umask=000,shortname=winnt,uid=knoppix,gid=knoppix 0 0
web@lohgoamd:~$ su
password:
root@lohgoamd:/home/web# vi /etc/fstab
root@lohgoamd:/home/web# exit
web@lohgoamd:~$ tail -3 /etc/fstab
/dev/hda1 /media/hda1 auto noauto,users,exec 0 0
# added by knoppix
/dev/sda1 /media/sda1 vfat noauto,users,exec,umask=000,shortname=winnt 0 0
web@lohgoamd:~$ mount /media/sda1/
web@lohgoamd:~$     

Philosophy

Category: Old hardware
So what should we do, long-term, with old -- really old -- hardware? With a notebook likely there isn't much that can be done. But perhaps for an old PC it would be possible to obtain appropriate memory chips -- the most important consideration in improving performance -- such that it becomes responsive enough for use with OpenOffice and Co.
Linux is supposed to be able to deal well with "old" hardware. True? I certainly think so. This test was unfair in the sense that it involved a notebook. They are notorious for creating problems... proprietary stuff is like that.
In booting this now-ancient notebook, Knoppix had far less trouble than my favorite distribution at the time. PCMCIA was a significant problem then. With Knoppix -- ho, hum... all my notes about "noacpi" and "nopcmcia" as kernel boot parameters were suddenly irrelevant.
But when is this a reasonable thing to do? I already mentioned that in my estimation, in this environment OpenOffice is effectively unusable because it's egregiously slow. Perhaps OK for collecting e-mail? Learning how to use OpenOffice? With only a serial interface available, this machine won't be used to access the Internet anymore.
I still haven't decided whether/how to use this newly available resource. Somehow, it seems inherently unreasonable to expect up-to-date desktop performance from old hardware, regardless of how recent the software release may be.
Perhaps I should have tried Damn Small Linux -- I didn't. Knoppix is BIG. Their 5.0 version on CD belongs in your tool-box but it isn't a server, and it wants X and KDE. That's a bit too rich for a basic system.
So, what should we do, long-term, with old -- really old -- hardware? With a notebook likely there isn't much that can be done. But perhaps for an old PC it would be possible to obtain appropriate memory chips -- the most important consideration in improving performance -- such that it becomes responsive enough for use with OpenOffice and Co.
Nonetheless, I had no trouble using it -- appropriately -- to write this article. As so often in life, a matter of picking and choosing one's tools (in this case Opera and Firefox and vi) and how one uses them.

 

 

Installing Knoppix in a Partition on a PC

The procedure in this situation is almost identical, so I won't bother with screen-shots that are the same. More important are the preparations beforehand and what might have to happen afterwards.
In this case, Knoppix is not supposed to take over the entire hard drive but just occupy one partition. If you don't have a partition available, likely it is best to first re-partition with familiar tools before starting the installation process. At least that's what I chose to do.
One of the nice things about using Knoppix is that installation does not take place in an unfamiliar and restricted environment; it is done through a script that runs after having booted Knoppix. In other words we have a familiar Linux environment, multiple windows and virtual terminals, and should the need arise, can do something that wasn't anticipated without having to cancel the installation and start over.
The installation script shows available partitions and asks you to select one. Any partitions that are too small for Knoppix won't be included in the list, so if you want a particular partition to be used and it isn't offered, you will have to cancel installation and increase the size of that partition (very often, that requires re-booting to get the system to use the new partition table). Unfortunately, Knoppix doesn't tell you this magic number. The DVD version of Knoppix 5.0.1 required about 11.5 GB.
Since this machine already has a couple of installations, it wouldn't be appropriate to replace the MBR - but that doesn't seem to be an option. So, let's back it up to a memory stick for later re-installation (thanks to Kyle Rankin):
sudo dd if=/dev/hda of=/media/sdb1/mbr_pc2 bs=512 count=1
After installation, restore the MBR (with a block size to omit the partition table) with something like this:
sudo dd if=/media/sdb1/mbr_pc2 of=/dev/hda bs=446 count=1
By the way, having to do it this way isn't necessarily a bug but can be considered a feature: you don't have to figure out what Grub needs in order to boot Knoppix. After installation, I copied /boot/grub/menu.lst to /media/sdb1/knoppix_grub and later copied the relevant sections from it to the file menu.lst in the partition normally used for booting.
Although this worked, it was Debian and I was still interested in having Knoppix as I know it. And as it turned out, this wasn't particularly difficult: when given the option to do so, save the configuration file somewhere convenient, then make modifications as desired. Here is what I used.
Having done that, you will need to load the configuration when given the opportunity before starting installation.


The screen where you can review the installation options then reflects these changes.
Strangely enough, booting failed with an error message from Grub. The command "savedefault" was followed by "Error 15: File not found". I didn't want to change the default anyhow and just commented out that command. Here is what I added to menu.lst. Since making that change, there have been no problems booting.

Conclusion

By today's standards this PC is getting on in age -- it's almost 3 years old. Something newer would definitely boot a bit faster: it takes some 5 minutes from the point in time that Grub is told which partition to boot. No surprise, considering that Knoppix goes through its usual check of available hardware. Maybe Debian would be better?
Quite some time ago, I was playing with a system that had an option to write status information to the swap space when the system was shut down. This could then be used on boot to speed the process up. I haven't looked for this with Knoppix, but it seems like a worthwhile idea.
One of the reasons that installation is so easy is that there are no confusing questions about what software to install. The downside is that an installation is way over 4 times the size of what I typically install with SuSE. Well, today hard drives are huge and cheap.
Worth note is that both SuSE and Knoppix start user IDs with 1000 -- I wonder if that has to do with conformance to LSB? Well, maybe not: just checked and Fedora Core 6 uses 500 as did SuSE a couple of releases back. Heck, I dunno. At least on a SuSE machine making an existing /home available should be possible (a task for another day.) The name change of the first user from whatever to knoppix, I could live with. Yeah, I know, that's not useful for a big environment -- but this is a small home office.
Before connecting to a network, you ought to consider following the advice of Klaus Knopper and modify /etc/sudoers. I did what he suggested and you can see that here.
The use of virtual terminals is different from that of SuSE or Red Hat; X runs on 5 rather than 7. Not a problem, but I did have to go looking the first time I wanted to return to KDE after having used a command line in a VT.
Although Knoppix belongs in everybody's tool box, it may not be your choice for a desktop environment. However, it is interesting having essentially the same system (5.0 vs 5.0.1) on both my notebook and my PC. I am looking forward to gaining more experience with this configuration once networking is set up and it is possible to do things like using X11 forwarding to start OpenOffice on the PC and use it from the notebook.

#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <vivek@nixcraft.com>
#
# Latest version can be found at http://www.nixcraft.com/
#
# Q2. Script to find out bigest number
#
# Algo:
#      1) START: Take three nos as n1,n2,n3.
#      2) Is n1 is greater than n2 and n3, if yes 
#         print n1 is bigest no goto step 5, otherwise goto next step
#      3) Is n2 is greater than n1 and n3, if yes 
#         print n2 is bigest no goto step 5, otherwise goto next step
#      4) Is n3 is greater than n1 and n2, if yes 
#         print n3 is bigest no goto step 5, otherwise goto next step
#      5) END
#
#
 
    if [ $# -ne 3 ]
    then
        echo "$0: number1 number2 number3 are not given" >&2
        exit 1    
    fi
    n1=$1
    n2=$2
    n3=$3
    if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
    then
        echo "$n1 is Bigest number"
    elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]         
    then
        echo "$n2 is Bigest number"
    elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]         
    then
        echo "$n3 is Bigest number"
    elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
    then
        echo "All the three numbers are equal"    
    else
        echo "I can not figure out which number is biger"    
    fi    
 
 

#!/bin/bash
# Q3
# Algo:
#       1) START: set value of i to 5 (since we want to start from 5,    
           if you want to start from other value put that value)
#       2) Start While Loop
#       3) Chechk, Is value of i is zero, If yes goto step 5 else
#          continue with next step
#       4) print i, decement i by 1 (i.e. i=i-1 to goto zero) and
#          goto step 3
#       5) END
#
i=5
while test $i != 0
do
        echo "$i
"
        i=`expr $i - 1`
done
#


#!/bin/bash
#
#
# Q5
#
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"
 
#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#
#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <vivek@nixcraft.com>
#
# Latest version can be found at http://www.nixcraft.com/
#
# Script to reverse given no
#
# Algo:
#       1) Input number n
#       2) Set rev=0, sd=0
#       3) Find single digit in sd as n % 10 it will give (left most digit)
#       4) Construct revrse no as rev * 10 + sd
#       5) Decrment n by 1
#       6) Is n is greater than zero, if yes goto step 3, otherwise next step
#       7) Print rev
#
if [ $# -ne 1 ]
then
    echo "Usage: $0   number"
    echo "       I will find reverse of given number"
    echo "       For eg. $0 123, I will print 321"
    exit 1
fi
 
n=$1
rev=0
sd=0
 
while [ $n -gt 0 ]
do
    sd=`expr $n % 10`
    rev=`expr $rev \* 10  + $sd`
    n=`expr $n / 10`
done
    echo  "Reverse number is $rev"
 
#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#



#!/bin/bash
#
# Linux Shell Scripting Tutorial 1.05r3, Summer-2002
#
# Written by Vivek G. Gite <vivek@nixcraft.com>
#
# Latest version can be found at http://www.nixcraft.com/
#
# Algo:
#       1) Input number n
#       2) Set sum=0, sd=0
#       3) Find single digit in sd as n % 10 it will give (left most digit)
#       4) Construct sum no as sum=sum+sd
#       5) Decrment n by 1
#       6) Is n is greater than zero, if yes goto step 3, otherwise next step
#       7) Print sum
#
if [ $# -ne 1 ]
then
    echo "Usage: $0   number"
    echo "       I will find sum of all digit for given number"
    echo "       For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
    exit 1
fi
 
n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
    sd=`expr $n % 10`
    sum=`expr $sum + $sd`
    n=`expr $n / 10`
done
    echo  "Sum of digit for numner is $sum" 
 
#
# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool
# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/
#

No comments:

Post a Comment