Unix practical file


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Unix practical file

  1. 1. INDEXS.No Date Topic Sign Remarks1. Performing Arithmetic Operations2. Comparison between two numbers3. Comparison between three numbers4. Combination of subjects5. Compound Interest Calculation6. Counting of numbers7. Sum of 5 digit numbers8. Check even /odd9. Display Fibonacci Series10. Find out HCF11. Find out LCM12. Find out Leap year13. Perform Exponential Function14. Check prime number15. Calculate Simple Interest16. Swap two numbers without using three variables17. Display Table of any number18. Perform concatenation of a string19. Convert Celsius temperature into Fahrenheit20. Check whether a number is a palindrome21. Menu for all of the above coding
  2. 2. UNIX BASICS1.0 IntroductionThe purpose of this document is to provide the reader with a fast and simple introduction to using the Linux command shelland some of its basic utilities. It is assumed that the reader has zero or very limited exposure to the Linux command prompt.This document is designed to accompany an instructor-led tutorial on this subject, and therefore some details have been leftout. Explanations, practical examples, and references to DOS commands are made, where appropriate.1.1 What is a command shell? A program that interprets commands Allows a user to execute commands by typing them manually at a terminal, orautomatically in programs called shell scripts. A shell is not an operating system. It is a way to interface with the operatingsystem and run commands.1.2 What is BASH? BASH = Bourne Again SH SHell Bash is a shell written as a free replacement to the standard Bourne Shell (/bin/sh) originally written by Steve Bourne forUNIX systems. It has all of the features of the original Bourne Shell, plus additions that make it easier to program withand use from the command line. Since it is Free Software, it has been adopted as the default shell on most Linux systems.1.3 How is BASH different from the DOS command prompt? Case Sensitivity: In Linux/UNIX, commands and filenames are case sensitive, meaning that typing “EXIT” instead ofthe proper “exit” is a mistake. “ ” vs. “/”: In DOS, the forward-slash “/” is the command argument delimiter, while the “/backslash “” is a directory separator. In Linux/UNIX, the “/” is the directory separator, and the “” is an escape character.More about these special characters in a minute! Filenames: The DOS world uses the “eight dot three” filenameconvention, meaning that all files followed a format that allowed up to 8 characters in the filename, followed by a period(“dot”), followed by an option extension, up to 3 characters long (e.g. FILENAME.TXT). In UNIX/Linux, there is no suchthing as a file extension. Periods can be placed at any part of the filename, and “extensions” may be interpreted differentlyby all programs, or not at all.1.4 Special CharactersBefore we continue to learn about Linux shell commands, it is important to know that there are many symbols andcharacters that the shell interprets in special ways. This means that certain typed characters: a) cannot be used in certainsituations, b) may be used to perform special operations, or, c) must be “escaped” if you want to use them in a normal way.Character Description Escape character. If you want to reference a special character, you must “escape” it with a backslash first.Example: touch /tmp/filename* / Directory separator, used to separate a string of directory names.Example: /usr/src/linux . Current directory. Can also “hide” files when it is the first character in a filename... Parent directory~ Users home directory* Represents 0 or more characters in a filename, or by itself, all files in a directory.Example: pic*2002 can represent the files pic2002, picJanuary2002,picFeb292002, etc.? Represents a single character in a filename.Example: hello?.txt can represent hello1.txt, helloz.txt, but nothello22.txt[ ] Can be used to represent a range of values, e.g. [0-9], [A-Z], etc.Example: hello[0-2].txt represents the names hello0.txt,hello1.txt, and hello2.txt| “Pipe”. Redirect the output of one command into another command.Example: ls | more> Redirect output of a command into a new file. If the file already exists, over-write it.Example: ls > myfiles.txt>> Redirect the output of a command onto the end of an existing file.Example: echo .Mary 555-1234. >> phonenumbers.txt< Redirect a file as input to a program.
  3. 3. Example: more < phonenumbers.txt; Command separator. Allows you to execute multiple commands on a single line.Example: cd /var/log ; less messages && Command separator as above, but only runs the second command if the first onefinished without errors.Example: cd /var/logs && less messages & Execute a command in the background, and immediately get your shell back.Example: find / -name core > /tmp/corefiles.txt &1.5 Executing Commands The Command PATH: Most common commands are located in your shells “PATH”, meaning that you can just type the name of the program toexecute it. Example: Typing “ ls” will execute the “ ls” command. Your shells “PATH” variable includes the most commonprogram locations, such as /bin, /usr/bin, /usr/X11R6/bin, and others. To execute commands that are not in your current PATH, you have to give the completelocation of the command. Examples: /home/bob/myprogram ./program (Execute a program in the current directory)~/bin/program (Execute program from a personal bin directory)Command Syntax Commands can be run by themselves, or you can pass in additional arguments to make them do different things. Typicalcommand syntax can look something like this: command [-argument] [-argument] [--argument] [file] Examples: ls Listfiles in current directory ls -l Lists files in “long” format ls -l --color As above, with colourized output cat filename Showcontents of a file cat -n filename Show contents of a file, with line numbers2.0 Getting HelpWhen youre stuck and need help with a Linux command, help is usually only a few keystrokes away! Help on most Linuxcommands is typically built right into the commands themselves, available through online help programs (“man pages” and“info pages”), and of course online.2.1 Using a Commands Built-In HelpMany commands have simple “help” screens that can be invoked with special command flags. These flags usually look like “-h” or “--help”. Example: grep --help2.2 Online Manuals: “Man Pages”The best source of information for most commands can be found in the online manual pages, known as “man pages” forshort. To read a commands man page, type “man command”. Examples: man ls Get help on the “ls” command. man man Amanual about how to use the manual! To search for a particular word within a man page, type “/word”. To quit from a manpage, just type the “Q” key. Sometimes, you might not remember the name of Linux command and you need to search for it.For example, if you want to know how to change a files permissions, you can search the man page descriptions for the word“permission” like this:man -k permission If you look at the output of this command, you will find a line that looks something like: chmod (1) -change file access permissions Now you know that “chmod” is the command you were looking for. Typing “man chmod” willshow you the chmod commands manual page!2.3 Info PagesSome programs, particularly those released by the Free Software Foundation, use info pages as their main source of onlinedocumentation. Info pages are similar to man page, but instead of being displayed on one long scrolling screen, they arepresented in shorter segments with links to other pieces of information. Info pages are accessed with the “info” command, oron some Linux distributions, “pinfo” (a nicer info browser).For example: info df Loads the “df” info page.3.0 Navigating the Linux File systemThe Linux filesystem is a tree-like hierarchy hierarchy of directories and files. At the base of the filesystem is the “/”directory, otherwise known as the “root” (not to be confused with the root user). Unlike DOS or Windows filesystems thathave multiple “roots”, one for each disk drive, the Linux filesystem mounts all disks somewhere underneath the / filesystem.The following table describes many of the most common Linux directories.3.1 The Linux Directory LayoutDirectory Description
  4. 4. The nameless base of the filesystem. All other directories, files, drives, and devices are attached to this root. Commonly (butincorrectly) referred to as the “slash” or “/” directory. The “/” is just a directory separator, not a directory itself./bin Essential command binaries (programs) are stored here (bash, ls, mount, tar, etc.)/boot Static files of the boot loader./dev Device files. In Linux, hardware devices are acceessd just like other files, and they are kept under this directory./etc Host-specific system configuration files./home Location of users personal home directories (e.g. /home/susan)./lib Essential shared libraries and kernel modules./proc Process information pseudo-filesystem. An interface to kernel data structures./root The root (superuser) home directory./sbin Essential system binaries (fdisk, fsck, init, etc)./tmp Temporary files. All users have permission to place temporary files here./usr The base directory for most shareable, read-only data (programs, libraries,documentation, and much more)./usr/bin Most user programs are kept here (cc, find, du, etc.)./usr/include Header files for compiling C programs./usr/lib Libraries for most binary programs./usr/local “Locally” installed files. This directory only really matters in environments where files are stored on the network.Locally-installed files go in /usr/local/bin, /usr/local/lib, etc.). Also often used forsoftware packages installed from source, or software not officially shipped with the distribution./usr/sbin Non-vital system binaries (lpd, useradd, etc.)/usr/share Architecture-independent data (icons, backgrounds, documentation, terminfo, man pages, etc.)./usr/src Program source code. E.g. The Linux Kernel, source RPMs, etc./usr/X11R6 The X Window System./var Variable data: mail and printer spools, log files, lock files, etc.3.2 Commands for Navigating the Linux FilesystemsThe first thing you usually want to do when learning about the Linux filesystem is take some time to look around and seewhats there! These next few commands will: a) Tell you where you are, b) take you somewhere else, and c) show you whatsthere. The following table describes the basic operation of the pwd, cd, and ls commands, and compares them to certain DOScommands that you might already be familiar with.Linux Command DOS Command Descriptionpwd cd “Print Working Directory”. Shows the current location in the directory tree.cd cd, chdir “Change Directory”. When typed all by itself, it returns you to your home directory.cd directory cd directory Change into the specified directory name. Example: cd /usr/src/linuxcd ~ “~” is an alias for your home directory. It can be used as a shortcut to your “home”, or otherdirectories relative to your home.cd .. cd.. Move up one directory. For example, if you are in /home/vic and you type “cd ..”, you will endup in /home.cd - Return to previous directory. An easy way to get back to your previous location!ls dir /w List all files in the current directory, in column format.ls directory dir directory List the files in the specified directory. Example: ls /var/logls -l dir List files in “long” format, one file per line. This also shows you additional info about the file, suchas ownership, permissions, date, and size.ls -a dir /a List all files, including “hidden” files. Hidden files are those files that begin with a “.”, e.g. The.bash_history file in your home directory.ls –ld directoryA “long” list of “directory”, but instead of showing the directory contents, show the directorys detailedinformation. For example, compare the output of the following two commands:ls -l /usr/binls -ld /usr/binls /usr/bin/d* dir d*.* List all files whose names begin with the letter “d” in the /usr/bin directory.4.0 Piping and Re-DirectionBefore we move on to learning even more commands, lets side-track to the topics of piping and re-direction. The basic UNIXphilosophy, therefore by extension the Linux philosophy, is to have many small programs and utilities that do a particular
  5. 5. job very well. It is the responsibility of the programmer or user to combine these utilities to make more useful commandsequences.4.1 Piping Commands TogetherThe pipe character, “|”, is used to chain two or more commands together. The output of the first command is “piped” intothe next program, and if there is a second pipe, the output is sent to the third program, etc. For example: ls -la /usr/bin |lessIn this example, we run the command “ls -la /usr/bin”, which gives us a long listing of all of the files in /usr/bin. Becausethe output of this command is typically very long, we pipe the output to a program called “less”, which displays the outputfor us one screen at a time.4.2 Redirecting Program Output to FilesThere are times when it is useful to save the output of a command to a file, instead of displaying it to the screen. Forexample, if we want to create a file that lists all of the MP3 files in a directory, we can do something like this, using the “>”redirection character: ls -l /home/vic/MP3/*.mp3 > mp3files.txtA similar command can be written so that instead of creating a new file called mp3files.txt, we can append to the end of theoriginal file: ls -l /home/vic/extraMP3s/*.mp3 >> mp3files.txt5.0 Other Linux CommandsThe following sections describe many other commands that you will find on most Linux systems. I cant possibly cover thedetails of all of these commands in this document, so dont forget that you can check the “man pages” for additionalinformation. Not all of the listed commands will be available on all Linux or UNIX distributions.5.1 Working With Files and DirectoriesThese commands can be used to: find out information about files, display files, and manipulate them in other ways (copy,move, delete).LinuxCommandDOSCommandDescriptionfile Find out what kind of file it is.For example, “file /bin/ls” tells us that it is a Linux executable file.cat type Display the contents of a text file on the screen. For example: cat mp3files.txt would display the file we created inthe previous section.head Display the first few lines of a text file. Example: head /etc/servicestail Display the last few lines of a text file. Example: tail /etc/servicestail -f Display the last few lines of a text file, and then output appended data as the file grows (very useful for followinglog files!). Example: tail -f /var/log/messagescp copy Copies a file from one location to another. Example: cp mp3files.txt /tmp (copies the mp3files.txt file to the /tmpdirectory)mv rename,ren, moveMoves a file to a new location, or renames it. For example: mv mp3files.txt /tmp (copy the file to /tmp, and delete it fromthe original location)rm del Delete a file. Example: rm /tmp/mp3files.txtmkdir md Make Directory. Example: mkdir /tmp/myfiles/rmdir rd, rmdir Remove Directory. Example: rmdir /tmp/myfiles/5.2 Finding ThingsThe following commands are used to find files. “ls” is good for finding files if you already know approximately where theyare, but sometimes you need more powerful tools such as these:LinuxCommandDescription
  6. 6. which Shows the full path of shell commands found in your path. For example, ifyou want to know exactly where the“grep” command is located on the filesystem, you can type “which grep”. The output should be something like: /bin/grepwhereis Locates the program, source code, and manual page for a command (if all information is available). For example, tofind out where “ls” and its man page are, type: “whereis ls” The output will look something like: ls: /bin/ls/usr/share/man/man1/ls.1.gzlocate A quick way to search for files anywhere on the filesystem. For example, you can find all files and directories thatcontain the name “mozilla” by typing: locate mozillafind A very powerful command, but sometimes tricky to use. It can be used to search for files matching certain patterns, aswell as many other types of searches. A simple example is:find . -name *mp3This example starts searching in the current directory “.” and all subdirectories, looking for files with “mp3” at the end oftheir names.5.3 Informational CommandsThe following commands are used to find out some information about the user or the system.Linux Command Explanationps Lists currently running process (programs).w Show who is logged on and what they are doing.id Print your user-id and group idsdf Report filesystem disk space usage (“Disk Free” is how I remember it)du Disk Usage in a particular directory. “du -s” provides a summary for the current directory.top Displays CPU processes in a full-screen GUI. A great way to see the activity on your computer in real-time. Type “Q” toquit.free Displays amount of free and used memory in the system.cat /proc/cpuinfo Displays information about your CPU.cat /proc/meminfo Display lots of information about current memory usage.uname -a Prints system information to the screen (kernel version, machine type, etc.)5.4 Other UtilitiesHere are some other commands that are useful to know.Linux Command Descriptionclear Clear the screenecho Display text on the screen. Mostly useful when writing shell scripts. For example: echo “Hello World”more Display a file, or program output one page at a time. Examples:more mp3files.txtls -la | moreless An improved replacement for the “more” command. Allows you to scroll backwards as well as forwards.grep Search for a pattern in a file or program output. For example, to find out which TCP network port is used by the “nfs”service, you can do this:grep .nfs. /etc/servicesThis looks for any line that contains the string “nfs” in the file “/etc/services” and displays only those lines.lpr Print a file or program output. Examples:lpr mp3files.txt - Print the mp3files.txt filels -la | lpr - Print the output of the “ls -la” command.sort Sort a file or program output. Example: sort mp3files.txtsu “Switch User”. Allows you to switch to another users account temporarily.The default account to switch to is the root/superuser account. Examples:su - Switch the root accountsu - - Switch to root, and log in with roots environmentsu larry - Switch to Larrys account5.5 Shortcuts to Make it all Easier!When you start using the Bash shell more often, you will appreciate these shortcuts that can save you very much typingtime.Shortcut DescriptionUp/Down Arrow Keys Scroll through your most recent commands. You can scroll back to an old command, hit ENTER,and execute the command without having to re-type it. “history” command Show your complete command history. TAB
  7. 7. Completion If you type a partial command or filename that the shell recognizes, you can have it automatically completed foryou if you press the TAB key. Try typing the first few characters of your favourite Linux command, then hit TAB a coupleof times to see what happens. Complete recent commands with “!” Try this: Type “!” followed by the first couple of letters ofa recent command and press ENTER! For example, type: find /usr/bin -type f -name m* ...and now type:!fiSearch your command history withCTRL-RPress CTRL-R and then type any portion of a recent command. It will search the commands for you, and once you find thecommand you want, just press ENTER. Scrolling the screen with Shift- PageUp and Page DownScroll back and forward through your terminal. 1. Common Arithmetic operations a) Additionecho enter two numbersread a badd=`expr $a + $b`echo $add b) Subtraction
  8. 8. echo enter two numbersread a bsub=`expr $a - $b`echo $sub c) Multiplicationecho enter two numbersread a bmul=`expr $a * $b`echo $mul d) Divisionecho enter two numbersread a bdiv=`expr $a / $b`
  9. 9. echo $div 2. Biggest of Two Numbersecho enter two numbersread a bif test $a -gt $bthenecho first number is greaterelseecho second number is greaterfi 3. Biggest Among Three Numbers
  10. 10. echo enter three different numbersread a b cif test $a -gt $bthenif test $a -gt $cthenecho number first is greatestelseecho third number is greatestfielif test $b -gt $cthenecho number second is greatestelseecho third number is greatestfi 4. Implementation of Combination
  11. 11. echo Combination of subjects in objects:echo Enter the number of objectsread necho Enter the subjects you chooseread rp=1q=1m=1if test $r -gt $nthenecho Subjects can not be greater than Objectsexitfix=`expr $n - $r`while [ $n -gt 0 ]dop=`expr $p * $n`n=`expr $n - 1`donewhile [ $r -gt 0 ]doq=`expr $q * $r`r=`expr $r - 1`
  12. 12. donewhile [ $x -gt 0 ]dom=`expr $m * $x`x=`expr $x - 1`doneq=`expr $q *$m`c=`expr $p / $q`echo Number of combinations will be : $c 5. Compound Interest Computationecho We are going to calculate Compound Interestecho Please enter Principalread pecho Rate of Interest already divided by 100read recho Years After which getting interestread tx=`echo $r + 1 | bc`n=1i=1while [ $n -le $t ]
  13. 13. doi=`echo $i * $x | bc`n=`echo $n + 1 | bc`donei=`echo $i * $p | bc`ci=`echo $i - $p | bc`echo Compound Interest will be : $ci 6. Counting upto any Required Numberecho Enter any numberread aecho Here Counting Startsn=1while [ $n -le $a ]doecho $nn=`expr $n + 1`done 7. Sum of Digits of any 5-digit Number
  14. 14. echo Enter any 5 digit numberread ab=0while [ $a -gt 0 ]doc=`expr $a % 10`a=`expr $a / 10`b=`expr $b + $c`doneecho Its sum will be $b 8. Find Out Whether a Number is Even or Odd? echo Enter any number
  15. 15. read ab=`expr $a % 2`if test $b -eq 0thenecho You entered an even numberelseecho You entered an odd numberfi 9. Fibonacci Series Displayecho enter any numberread ax=0y=1z=0echo Fibonacci Series upto $a will be:echo $xecho $ywhile [ $a -ge $z ]doz=`expr $x + $y`if test $z -ge $a
  16. 16. thenexitfiecho $zx=`expr $y`y=`expr $z`done 10.HCF Calculationecho Enter two different numbersread a bx=1y=1if test $a -eq 1thenecho HCF is 1exitelif test $b -eq 1thenecho HCF is 1exitfi
  17. 17. n=1f=1if test $a -lt $bthenn=$ax=$ay=$belsen=$bx=$by=$afiwhile [ $n -ge 2 ]doc=`expr $x % $n`if test $c -eq 0then d=`expr $y % $n` if test $d -eq 0 then echo HCF is $n exit fifin=`expr $n - 1`f=0doneif test $f -eq 0thenecho HCF is 1fi
  18. 18. 11.LCM Calculationecho Enter two numbersread a bn=1x=1y=1r=1if test $a -eq 1thenecho LCM is $bexitelif test $b -eq 1thenecho LCM is $aexitfiif test $a -gt $bthenx=$ay=$belsex=$by=$a
  19. 19. fiwhile [ $n -le $x ]dor=`expr $x * $n`res=`expr $r % $y`if test $res -eq 0thenecho LCM is $rexitfin=`expr $n + 1`done 12.Find Out Whether an year is Leap or not?echo Enter the year valueread ax=`expr $a % 4`if test $x -eq 0thenecho Its a leap year
  20. 20. elseecho Its not a leap yearfi 13.Calculation using Exponential Functionecho Calculating exponential functionecho Enter Baseread aecho Enter Exponentread bn=1x=1while [ $b -ge $n ]dox=`expr $x * $a`n=`expr $n + 1`doneecho $a to the power $b is equal to $x
  21. 21. 14.Find Out Whether a Number is Prime? echoEnter any numberread ab=`expr $a / 2`if test $b -eq 1thenecho Number is primefin=2x=0while [ $b -ge $n ]doc=`expr $a % $n`if test $c -eq 0thenecho Number is not primex=0breakelsex=1fin=`expr $n + 1`done
  22. 22. if test $x -eq 1thenecho Number is primefi 15.Simple Interest Calculationecho We are going to calculate Simple Interestecho Enter Principalread aecho Rate of Interestread becho Years for which you want SIread csi=`expr $a * $b * $c / 100`
  23. 23. echo Then Simple interest will be $si 16.Swapping two Numbers Using Two Variables echoEnter two numbersread x yif test $x -gt $ythenx=`expr $x - $y`y=`expr $x + $y`x=`expr $y - $x`elsey=`expr $y - $x`x=`expr $x + $y`y=`expr $x - $y`fiecho Swapped Value: $x and $yecho Hence swapping done
  24. 24. 17.Displaying Table of any Numberecho Enter any numberread an=1echo Its table will bewhile [ $n -lt 11 ]dob=`expr $a * $n`echo "$a * $n = $b"n=`expr $n + 1`done
  25. 25. 18.String Operationsecho String Concatenationecho Enter First Stringread aecho Now second Stringread becho Concatenated String : $a $b
  26. 26. 19.Temperature Conversion of Celsius into Farenheit echo Enter Temperature in celsius read c c=`echo $c * 9 | bc` c=`echo $c / 5 | bc` c=`echo $c + 32 | bc` echo Hence Temperature in Farenheit : $c 20.Checking Palindromeecho Checking Palindromeecho give input numberread ad=`expr $a`c=0
  27. 27. while [ $d -gt 0 ]dob=`expr $d % 10`d=`expr $d / 10`c=`expr $c * 10 + $b`doneif test $a -eq $cthenecho The Given number is Palindromeelseecho The number is not a Palindromefi 21.Menu Driven Programs List echo "what you want to do? 1. Perform Arithmetic Operations 2. Digit Sum 3. Comparison of 2 numbers 4. Comparison of 3 numbers 5. Celsius to Fahrenheit 6. Combination 7. Permutation 8. Compound Interest 9. Even or Odd 10. Fibonacci Series upto a specified number 11. HCF of two numbers 12. LCM of two numbers 13. Leap Year determination
  28. 28. 14. Palindrome15. Whole number Exponent calculation16. Prime number detection17. Simple Interest Calculation18. Table of a specified number19. Exchanging two numbers without a third variable20. Counting till a specified numberenter your choice......"read chcase $ch in1)echo "Select the operation you want to perform:"echo "1. Additionn2. Subtractionn3. Multiplicationn4. Divison"read choicecase $choice in1)read -p "Enter 2 numbers: " a bans=`expr $a + $b`echo "The answer is $ans";;2)read -p "Enter 2 numbers: " a bans=`expr $a - $b`echo "The answer is $ans";;3)read -p "Enter 2 numbers: " a bans=`expr $a * $b`echo "The answer is $ans";;4)read -p "Enter 2 numbers: " a bans=`expr $a / $b`echo "The answer is $ans";;esac2)read -p "Enter a 5 digit number: " numi=0mod=0sum=0for (( i = 0; $num != 0; i++ ))domod=`expr $num % 10`num=`expr $num / 10`sum=`expr $sum + $mod`
  29. 29. doneif test $i -gt 5thenecho "Next time please enter a number of 5 digits only."fiecho "The answer is: $sum"3)read -p "Enter 2 numbers: " a bif test $a -gt $bthenecho "$a is greater"elseecho "$b is greater"fi;;4)read -p "Enter 3 numbers: " a b cif test $a -gt $bthen if test $a -gt $c then echo "$a is greatest" else echo "$c is greatest" fielse if test $b -gt $c then echo "$b is greatest" else echo "$c is greatest" fifi;;5)read -p "Enter temperature in degrees celcius: " degctemp=`expr $degc * 9`temp=`expr $temp / 5`temp=`expr $temp + 32`echo "$degc degrees celcius is $temp fahrenheit.";;6)echo "enter the total number of objects"read necho "enter the selected number of objects"read r
  30. 30. if [ $r -gt $n ]thenecho "selected objects can not be greater than the total number of objects"elsed=`expr $n - $r`b=1while [ $n -gt 0 ]dob=`expr $b * $n`n=`expr $n - 1`donec=1while [ $d -gt 0 ]doc=`expr $c * $d`d=`expr $d - 1`donep=1while [ $r -gt 0 ]dop=`expr $p * $r`r=`expr $r - 1`doneq=`expr $c * $p`e=`expr $b / $q`fiecho $e;;7)echo "enter the total number of objects"read necho "enter the selected number of objects"read rif [ $r -gt $n ]thenecho "selected objects can not be greater than the total number of objects"elsed=`expr $n - $r`b=1while [ $n -gt 0 ]dob=`expr $b * $n`n=`expr $n - 1`donec=1while [ $d -gt 0 ]doc=`expr $c * $d`d=`expr $d - 1`
  31. 31. donee=`expr $b / $c`fiecho $e;;8)read -p "Enter the principal amount: " pread -p "Enter the rate of interest: " rread -p "Enter the time period: " ttemp=`expr $r / 100`temp=`expr $temp + 1`for ((i = 0; i < $t; i++))dotemp=`expr $temp * $temp`donetemp=`expr $p * $temp`temp=`expr $temp - $p`echo "n$temp is the interest.";;9)read -p "Enter any integer: " nummod=`expr $num % 2`if test $mod -eq 0thenecho "This integer is even."else echo "This integer is odd."fi;;10)read -p "Enter a limiting number: " numa=0b=1sum=0echo $afor ((i = 0; $sum <= $num; i++))doecho $bsum=`expr $a + $b`a=$bb=$sumdone;;
  32. 32. 11)echo enter two numbersread a bif [ $a -gt $b ]theni=`expr $a`j=`expr $b`elsei=`expr $b`j=`expr $a`fic=`expr $i % $j`while [ $c -ne 0 ]doi=`expr $j`j=`expr $c`c=`expr $i % $j`doneecho HCF is $j;;12)echo enter two numbersread a bif [ $a -lt $b ]theni=`expr $a`elsei=`expr $b`fiz=`expr $a * $b`while [ $i -ne $z ]dox=`expr $i % $b`y=`expr $i % $a`if [ $x -eq 0 -a $y -eq 0 ]thenbreakfii=`expr $i + 1`doneecho lcm of given numbers is : $i;;13)read -p "Enter a year: " yearmod=`expr $year % 100`if test $mod -eq 0thenmod=`expr $year % 400`
  33. 33. if test $mod -eq 0 then echo "This is a leap year." exit 0 else echo "This is not a leap year." exit 0 fielsemod=`expr $year % 4` if test $mod -eq 0 then echo "This is a leap year." exit 0 else echo "This is not a leap year." exit 0 fifi;;14)read -p "Enter a string: " strlen=`expr length $str`truth=1for((i = 1; $i <= $len && $truth == 1; i++))dos1=`expr substr $str $i 1`s2=`expr substr $str $len 1`if test $s1 = $s2thenlen=`expr $len - 1`elsetruth=0fidoneif test $truth -eq 1thenecho "This string is a palindrome!"elseecho "This string is not a palindrome"fi;;15)read -p "Enter any integer: " numread -p "Enter the power: " pow
  34. 34. ans=$numfor ((i = 1; i < $pow; i++))doans=`expr $num * $ans`doneecho "$num raised to power of $pow is: $ans";;16)read -p "Enter a number: " numsqrt=`expr "sqrt($num)" | bc`if test $num -eq 2thenecho "This is a prime number."exit 0elsechk23=`expr $num % 2` if test $chk23 -eq 0 then echo "This is not a prime number." exit 0 fifiif test $num -eq 3thenecho "This is a prime number."exit 0elsechk23=`expr $num % 3` if test $chk23 -eq 0 then echo "This is not a prime number." exit 0 fifik=0for((i = 1; $k <= $sqrt; i++))dok=`expr 6 * $i`k=`expr $k + 1`r1=`expr $num % $k`k=`expr $k - 1`k=`expr $k - 1`r2=`expr $num % $k`if test $r1 -eq 0 || test $r2 -eq 0then
  35. 35. echo "This is not a prime number."exit 0fidoneecho "This is a prime number.";;17)read -p "Enter the principal amount: " pread -p "Enter the rate of interest: " rread -p "Enter the time period: " ttemp=`expr $p * $r`temp=`expr $temp * $t`temp=`expr $temp / 100`echo "nThe simple interst is: $temp";;18)read -p "Enter any number: " numfor ((i = 1; i <= 10 ; i++))doecho "$num x $i = `expr $num * $i`"done;;19)read -p "Enter 2 numbers: " a ba=`expr $a + $b`b=`expr $a - $b`a=`expr $a - $b`echo "$a $b";;20)echo enter any numberread ai=0echo counting is:while [ $i -le $a ]doecho $ii=`expr $i + 1`done;;esac