Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Linux. Topics Covered  History of  Unix  Linux  Windows  Features of Unix  Introduction to Open Source Software  Comparison of.

Similar presentations


Presentation on theme: "Introduction to Linux. Topics Covered  History of  Unix  Linux  Windows  Features of Unix  Introduction to Open Source Software  Comparison of."— Presentation transcript:

1 Introduction to Linux

2 Topics Covered  History of  Unix  Linux  Windows  Features of Unix  Introduction to Open Source Software  Comparison of Windows and Linux  Using Linux  Unix/Linux File System  Commands  GUI  Tools  Shell Programming

3 History of Unix  The first version of UNIX was created in 1969 by Kenneth Thompson at AT&T Bell Laboratories. The operating system had four parts: the kernel, the shell, the editor, and the assembler.  The original name was UNICS which stands for UNiplexed Information and Computing Services. UNICS was later renamed to UNIX (UNIX is not an acronym).  Due to some limitations in assembly language, another computer scientist at Bell Labs, Dennis Richie, created a new programming language called C to continue improving UNIX.  UNIX was attractive to other organizations and universities for a few reasons:  It was the only powerful interactive system that could run on the sort of hardware that universities could afford in the mid ’70s.  It was written in an attractive language, C.  When UNIX got into the hands of many teachers and students and individuals around the world, it got further improved and became popular.  Some flavors are: AIX/PPCi (IBM), IRIX/MIPS (SGI), HP-UX/PA-RISC & Itanium (HP) True64/Alpha (DEC/Compaq) Solaris/SPARC/UltraSPARC (Sun/Oracle) SCO Unix (SCO), BSDi/x86 (BSDi)

4 Features of Uinux  The Kernel  Certain OS functions which are used almost continuously (like CPU scheduler, Disk Scheduler etc) are loaded permanently into memory for faster response. The memory resident part of an operating system is called the kernel.  Other OS functions which are used occasionally (such as create a file for example) are provided by utilities. These programs are invoked upon demand by the users.  Unix system attempts to keep the kernel small, so that, utility programs can provide most operating system functions. In contrast, many operating systems the kernel contains many features.

5 Features of Unix  Time Sharing  Time-sharing is a technique that has been developed for making a computer perform several jobs at once. The goal of time-sharing is to give each user the illusion of exclusive use of the machine.  Networking  Unix thoroughly supports various network protocols by default (like, TCP/IP, FTP, SMTP etc.)  User Interface  Unix provides a shell, where the user can run the commands to do the needful.  It also provides text editor(s) to create/modify text input files.  User Programs  Unix provides some compilers (at least C compiler) to create and run programs

6 GNU/FOSS  Around 1971, sharing of code was standard and common place.  Potential of software business was realized and by 80's code and hardware became commercial.  Around 1983 Richard Stallman who was working at MIT's AI lab had problems with a printer and tried to get the code but in vain.  All these things led Stallman to announce the GNU (GNU's Not Unix) project on the 27th September 1983.  Free Open Source Software (FOSS) was established.  All the software that we use today in our day to day work is the contribution by various individuals and organizations who selflessly donated code to the GNU/FOSS.

7 Linux  Linus Torvalds, a Sweedish speaking Fin, Studying Computer Science at Helsinki University started working with his 386DX, 33Mhz, 4MB RAM, no co-processor and a 40MB hard drive on a free Unix for the PC in the form of Minix ( written by Andrew Tannenbaum mainly as a teaching aid for computer OS design ).  On 25th August 1991, Linus made his famous post to Usenet. Proclaiming that he was working on a free operating system. Response to his posting was immediate.  In September 1991, Linux uploaded the first version (0.01) which was a massive 72K compressed). In 1992, it was made GPL.  Many enthusiasts contributed directly or through GNU, supported the project and it became very popular by 2000.  The compressed kernel source is now more than 20MB.  Now Linux runs on every system - from micro to super computers.

8 Windows  Paul Allen and Bill Gates, childhood friends with a passion in computer programming, established Microsoft on April 4, 1975, with Gates as the CEO.  Paul Allen and Bill Gates signed a contract with IBM in July 1980 inquiring about programming languages for its upcoming PC line. IBM gave Microsoft a contract to develop the OS (Disk Operating System - DOS) for their new line of PCs.  Following the release of the IBM PC in August 1981, Microsoft retained ownership of MS-DOS. Microsoft eventually became the leading PC operating systems vendor.  Microsoft released Microsoft Windows, a graphical extension for MS-DOS, on November 20, 1984.  Microsoft introduced its office suite, Microsoft Office, in 1990.  On May 22 Microsoft launched Windows 3.0. Both Office and Windows became dominant in their respective areas.  The company released Windows 95 on August 24, 1995, featuring pre-emptive multitasking  Later Windows released Windows 98, 2000, NT, XP, Windows Vista, Windows ME, Windows 7 etc. each improving the capabilities of the OS.

9 What Windows is missing? 1.Windows has a single-workspace desktop. Linux has multiple desktops for each user. 2. Windows has multiple accounts but not multiple concurrent users 3.Microsoft doesn’t include any useful applications (minus a browser) by default In Linux you don’t have to install an office suite, an email client, or audio/visual tools. 4. Windows security is weak.

10 Myths and Realities about Linux Free Software is not supported: The free software is supported by millions of solid programmers round the clock, and round the globe. Any error in software is almost guaranteed a correction with in a day. The proprietary software has to release a patch for that which may take ‘one day to any time’ depending on the intensity. Most of the bugs are even unattended. Free Software is not Secure: The source code is analyzed by people with both good and bad intensions. But it is already proved, that the people always fix the bugs. In proprietary software, nobody inspects the code other than those who developed it. Hence chances of finding bugs are less. Many security flaws are being reported regularly in proprietary software. Free software is of low quality: Free software is written for their satisfaction and hence total effort is put in developing the software. Though there are bugs initially, they will be fixed immediately.

11 Myths and Realities -- Continued.. Open Software is Linux: Linux is no doubt the most popular open software, but most of the tools that made Linux popular are also open software. Freedom software is non-integrated: The fact is that any change will be screened thoroughly and then only added to the actual code. It is this point that made open software so powerful. Open Software has no GUI It has better GUI than many commercial software. This is demonstrated later in this session. Literature is not available: More that a billion lines of help is available on various topics of Open Software. None of the commercial software has this much information. Moreover user groups are available for every application that is given free.

12 Features Available in Linux Standard Features: * File and data management tools * Backup/Recovery Tools * Networking & Internet Tools (Dialers, Browsers, email clients etc.) * Multimedia Applications (Audio/Video CD Players, Recorders, TV ) Software Development Tools: * Compilers, IDEs and Visual tools for almost all languages like C/ C++/ Java/ Fortran/ Basic/ Pascal (dozens of other languages) for free or Commercial Office Tools: * Star Office (Commercial @ around Rs.1500/-) * Open Office/ kOffice (free) Databases: * MySQL/ PostgreSQL/ Sybase/ IBM DB 2/MySQL

13 Industry Acceptance  Linux is the fastest growing OS  Linux is considered by Microsoft as a serious threat.  Linux is accepted as a sturdy OS now.  Many major companies have either shifted or seriously considering to shift to Unix Based Machines, particularly to Open Source.  It is now being used in many time critical applications, including military, space, business and scientific applications (where security is important).  Almost all hardware vendors are supporting Linux also. Even they are giving Linux pre-loaded machines.  On the server side, Linux is particularly strong where security and stability are of great importance.  In an office environment, Linux is sufficient where fancy hardware need not be supported.

14 Companies Supporting Linux  Almost all big players in the world recognized Linux as a stable operating system. It is particularly dominant on server side. Companies are given here though the list is by no means complete:  Oracle Corporation Inc  Google  IBM  Sybase  Borland  Novell  Veritas  BEA WebLogic,  SAP  BMC, CA, EMC, Legato, Rogue Wave and many others

15 Linux architecture  Any file/dir with a preceding dot is a hidden from ls command. To view them, use –a option.  Linux uses Modules that can be loaded dynamically and hence, doesn’t require reboot when a new driver is loaded.  Linux can use windows drivers directly in some cases with a bridge program.  Many windows programs can be installed and run with wine (windows emulator) Hardware dependent code Hardware System Call Interface GNU C Library (glibc) User Applications Kernel Kernel Space User Space

16 A finer view of the Linux/Unix System

17 Using Linux/Unix  Original Unix has only Command Line Interface (CLI)  Graphic User Interface was added with X Windows  CLI uses a shell that takes input from the user and sends output to the standard output  Linux and other flavors of Unix now support almost every possible command from both CLI and GUI, though sometimes a CLI is simple convenient (for example, Regular expressions).

18 Unix System Basics  Login  Every user should have an account to use the Unix machine.  When the machine boots, it presents a login screen, where the user enters the name and password and logs in.  For each user it runs a shell, and a prompt is shown on the screen in CLI or a desktop is shown in GUI.  The prompt symbol is different for different shells (# for root, $ for Bourne Shell and % for C Shell)  Logout  While leaving the machine, the user logs out of the system by issuing exit command (or by pressing ^D or ^C). If you forget to logout somebody else may misuse your login.

19 Files and Directories  Files  A file is a named collection of information. A computer file is analogous to a paper file stored in a filing cabinet.  Computer files have names, they can grow and shrink, they can be created and discarded, and they can be examined.  While naming files and directories, care may be taken to give meaningful and intuitive names. For example, a directory that contains test programmes may be named as test-progs.  Unix supports file names up 14 characters (old Systems) or 255 characters (new systems). It can be any printable character including numbers and special characters. However some characters may be avoided such as White Spaces (Space, New-line, and Tab Characters) and forward slash (/), which represents a directory.  Unix file names are case sensitive, i.e., files Test, test, TEST, TeSt are different.  Valid file names: abc, a.b.c.d, a~1.c, Host, HOST etc..  Invalid file names: 'a/a‘, ‘a”a’ etc.

20 Directory Structure  Directory is analogous to a file cabinet, which stores other directories or files. This is also known as Folder in Windows  Directories have the same naming convention as that of file names  Directory structure follows a tree structure, where the origin is the root, represented by a slash (/).  Slash is used as separator in specifying the hierarchy of directory  Ex: /usr/home/svln/Documents/abc.txt  Directory and File names are case sensitive (Unlike windows)  Abc.txt is different from abc.txt or aBc.txt  There are certain special directories in Unix  /etc – Unix configuration files  /usr – User space  /usr/lib – User libraries (partial code that can be used in other programs)  /usr/bin, /bin, /sbin – system and user executables  /var – System data area  /tmp – temporary file space  /home – Home directory for all users (each user has his/her own space) .,.. and ~/ – Current directroy (.) and parent directory (..) and user’s home (~/)

21 Directory Structure Example File a.doc has an absolute path of /home/svln/Docs/a.doc and a relative path w.r.t. svln is Docs/a.doc

22 CLI – Command line Interface  Generally Unix runs in two modes  Text Mode (Run level 0 to 3)  Graphical Mode (Run level 5)  Run levels can be changed while booting or by editing /etc/init.d/init.rc file

23 Unix Command Structure A command is a sequence of words separated by blanks or tabs. The first word of the command is the command's name. Subsequent words are the command's arguments. The simplest command is a single word.  For example the pwd (present working directory) command prints the name of the current directory. You can enter several commands on one line by separating the commands with semicolons.  $ pwd ; ls (Runs pwd and ls commands in sequence) Options (switches) can be added with -xx -yy... where each option modifies the behavior of the command.  For example ls -l command produces a long information of the current directory.

24 Command Structure contd. Arguments are added after the switches/modifiers/options separated by space or tab.  ls -l *.c (list all c files from the directory)  Command line arguments can take wildcard characters  * = zero or more characters  ? = Any one character  [abc] = Any one character in the set  [A-Z] = Any one character between A to Z (specifies range)  [a-z]  [0-9]  Other shell meta characters:  > Redirect output  < redirect input  >> Redirect and append output  Cmd1 || cmd2 (cmd1 Or cmd2 – Executes cmd2 when cmd1 fails)  Cmd1 && cmd2 (cmd1 And cmd2 – executes cmd2 when cmd1 is success)  $? – Result of last command

25 File and Directory Related Commands  ls = list files of a given directory  cd = Change directory to a given path  pwd = print the working directory  rm = remove given file/files  mv = move given file/files  cp = copy given file/files  chmod = change the permissions of a given file  chown = change ownership of a set of files  wc = word count counts lines words and characters in a file/files.  touch = changes the file time or creates a zero sized file if not exist  date = gets the system date  mkdir= create a new directory.  rmdir= remove directory

26 File Permissions  Users are grouped into user (u), group of the user (g) and all others (o)  Access level is defined as read (r), write (w) and execute (x)  Each of the group of users (u, g, o) can have any access permissions (r, w, x)  These are represented as 9 attributes where if permission is not given, a dash (-) is used.  Ex. rwxr-xr-x (User can r,w,x, group can r,x and others can r,x)  To change permissions, chmod command is used with the following syntax  chmod [who][+|-|=][mode... ] file.. (OR)  chmod xxx file, where x is a number between 0 to 7 indicating a 3 bit number  000 = 0 = ---, 001 = 1 = --x, 010 = 2 = -w-, 011 = 3 = -wx, 100 = 4 = r--,  101 = 5 = r-x, 110 = 6 = rw-, 111 = 7 = rwx  Special bits t and s may also be set if permissions are adequate.  The t-bit set only the owner of the file or directory can delete the files.  The t-bit can be set with chmod a+tw or chmod 1777  Executable files the that have the s-bit set on the group run under the group- ID of the file owner.  chmod 0755 suidtest (or) chmod u+s suidtest as root will run the program as root

27 More Useful commands  System Related:  service start|stop|restart|status  sudo command – Runs a command in root mode  su – Brings up a root user terminal  mount and umount – mount or unmount devices  passwd – Sets or deletes password for a given user  Process Related  top = Shows the process and resource information  ps = Shows processes of given user  kill = Kills a given process by its ID  I/O  echo [ -n ] [ arg ]... (outputs the arguments on to std output)  more, less  head, tail

28 Data Processing cut –f file cut –f 1-3,5-6, 8 test.dat (cut fields 1,2,3,5,6,8) cut –c 2-4,8-10 test.dat (cuts characters 2,3,4,8,9,10) cut –c 3, 5- test.dat (cuts characters 3, 5 to last char in the line) paste file1 file2.. paste a.dat b.dat (pastes a.dat and b.dat side by side on stdout) uniq file (lists only unique values from the file) sort [-t ] [-o outfile] file1 file2 … delimiter can be a single character (-t: colon is the field separator) -r reverse -n number sort -M month sort -f field list (field list contains pairs of values with +m and –n or single fields n1 n2 n3 etc. +m = skip first m fields -n = consider upto (inclusive) n-th field -d Dictionary order

29 Data Processing Contd.. sort sales –o sales (sort sales and save them again to sales file) sort +1 -2 +0 -1M sales (sorts sales based on field 2, then by field 1 by month) sort +2 -3nr +1 -2 +0 -1M sales (sorts on field 3 as numbers in reverse order, then by field 2 then by field 1 as month) Contents of sales: Mar 10 230 Jan 12 550 Apr 11 330 … tr ‘c1’ ‘c2’ replaces c1 with c2 on stdin tr ‘[a-z]’ ‘[A-Z]’ < abc.dat

30 crond and crontab  Cron is a daemon that executes scheduled commands.  The crontab command should be used to add or modify a command that is scheduled.  An example of crontab format with commented fields is as follows: # Minute Hour Day Month Day of Week Command # (0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat) 0 2 12 * 0,6 /usr/bin/find  This line executes the "find" command at 2AM on the 12th of every month that a Sunday or Saturday falls on.  Use crontab –e command to enter the commands.  Alternatively at command can be used for one time job at midnight echo “it is midnight” ^D

31 Find  find [action \;]  What can be -ctime n files last changed exactly n days ago -ctime +n files last changed more than n days ago -ctime –nfile last changed less than n days ago -size n [M|B]file size is exactly n blocks long (M= megabytes K=kilobytes) -size +nfile size is more than n blocks -size -nfile size is less than n blocks -name filenameSearch for the filename (file name can be any pattern including wild-cards) -type tfile type is t, where t can be any of (f =regular file, d =directory, b=block IO device, c = character IO device) -user unamefiles owned by user uname -group gnamefiles belong to the group gname  Action -exec command \;Execute the command. -exec command {} \;Execute the command after replacing the {} by the matching path name -ok command \;Execute the command after confirmation -ok command {} \;Executes the command after substitution with confiramtion -printPrints the result of the find. (Earlier, unless this action is used, output was not shown)  Ex: find. –name “*.dat” –exec cp {} /backup \; (copy all *.dat files to /backup)  find /usr/home/svl/tmp –size +20M –exec rm {} \; (find all files that are greater than 20MB in size are deleted from directory ~/tmp.

32 grep, egrep and fgrep  Commands of the grep family search the input files (or standard input if no files are specified) for lines matching a pattern. Normally, each matching line is copied to the standard output. If more than one file is being searched, the name of the file in which each match occurs is also written to the standard output along with the matching line (unless the -h option is used). grep [ -chilnsvy ] [ -f expfile] [ [-e] expression ] [ files ] egrep [ -chilnv ] [ -f expfile ] [ [-e] expression ] [ files ] fgrep [ -clnvxy ] [ -f expfile ] [ [-e] expression ] [ files ] grep - basic regular expressions egrep - uses extended regular expressions ( slowest ) fgrep - no regular expressions ( fastest ) egrep - same as grep -E ( extended-regexp ) fgrep - same as grep -F ( fixed-strings ) Extended re can use metacharacters like +, ?, | and ()

33 Grep family commands – contd..  Options  -v All lines but those matching are displayed.  -c Only a count of matching lines is displayed.  -l Only the names of files with matching lines are displayed, separated by new lines.  -h Prevents the name of the file from being printed, when searching multiple files. (Works with grep and egrep only. )  -n Each line is preceded by its relative line number in the file.  -i Turns on case insensitive matching of letters  -e expression or strings Same as a simple expression argument, but useful when the expression begins with a dash (-).  -f expfile The regular expression for grep or egrep, or strings list for fgrep is taken from the expfile.  In all cases (except with -h) the filename is output if there is more than one input file. Care should be taken when using the characters $ * [ ^ | ( ) and \ in expression, because they are also meaningful to the shell. It is safest to enclose the entire expression or strings argument in single quotation marks. For example:  grep '[Ss]omeone' text. file

34 Regular Expressions. - Any one character (“.ust” matches dust, must) ^ $ - begin and end of a line (“^x” matches lines starting with x and “yy$” matches lines end with yy) r* - matches any number of character r (ab* matches ab, abb …) [abc] – matches any one character from the set [^abc] – matches any character other than the set

35 egrep Regular Expressions Extensions + – one or more occurrences of r r? – zero or one occurrence of r r1|r2 – r1 or r2 (r1|r2)r3 – r1r3 or r2r3 (r1|r2)* - zero or more occurrences of r1 or r2 (ex: r2r1, r1r2, r1r1r1, r1r2r1 …) svl+ matches svl, svll, svlll etc. (svl)+ matches svl, svlsvl etc. svl? Matches sv, svl, svx, svg … (svl)? Matches “” and svl (svl)* matches “”, svl, svlsvl, svlsvlsvl, …

36 sed – Stream Editor  The stream editor (sed) uses the file stream as input and applies various ed commands on each line to modify the input.  Here the original file is not modified.  Only the output is modified.  The syntax for sed is:  sed [-n] [-e] ‘ ’  sed [-n] –f  The input file is taken line by line and the edit command supplied in single quotes is applied on each line.  In the first form, -e can be used to apply more than one ed command to each line simultaneously.  In the second form all the ed commands that are to be applied on each line are stored in a script file and then that file is supplied as the command file.

37 The following examples illustrate the use of sed: sed ‘s/june/july/g’ myfile  Replaces all occurrences of june with july. sed –e ‘s/june/july/g’ -e ‘s/january/december/’ myfile  Replace both june and january. sed ‘/Feb/q’ myfile  show all lines up to the first occurrence of ‘Feb’ and then quit. sed ‘1,4s/Feb/Mar/’ my file  Replace only in lines 1 to 4 inclusive. sed ‘/^Example/, /End$/s/Jan/Dec/g’ myfile  Replace Jan with Dec from line that begins with Example to the line that ends with End. sed ‘1,4!s/Jan/Dec/g’ myfile -> Replace on all but 1 to 4 lines. (! reverses the range) sed ‘1,4d’ myfile  deletes lines 1 to 4 sed ‘2a\ This is a new line added’ myfile  adds the line after the second line.(Observe a reverse slash at the end of the line.) sed ‘y/abc/ABC/’ myfile  replace a,b,c with A,B,C respectively sed –n ‘/Jan/p’ myfile  prints all the lines that contains Jan (Equivalent to grep) sed –n ‘/Jan/!p’ myfile  prints all lines that do not contain Jan.

38 awk  The word awk is derived from three names, Aho Weinberger and Kernighan, who created it.  awk is a programming language designed to process data from files or standard input.  It can search for patterns, and perform simple computations on files.  Awk has many variations  awk – Original Bell Labs awk  nawk – New awk  gawk – GNU implementation of awk standard.  ………  All versions support the standard POSIX (Portable Operating System Interface for Unix) but each may extend the features.

39 Basics of awk  awk reads data from a file or from standard input (Keyboard or redirected input), and writes data to standard output (screen in general).  awk considers each line as a record.  awk processes a file line by line, i.e., processes records in a sequence.  A record consists of fields separated by a delimiter. The delimiter can be any character (tab, space, colon, semicolon, or any user defined character) and the default is Tab/Space character.  Each field is represented by its number preceded by a $ sign.  i-th field is accessed with $i (field 1 with $1, ….)  $0 refers to the whole record.

40 awk Syntax  Syntax of awk:  awk [-F “ ”] ‘ { } ’ [‘ {actions} ’] … …  Pattern acts as a condition based on which action block is executed. Patterns can be regular expressions, arithmetic relational expressions, string-valued expressions, and arbitrary boolean combinations of these.  Action block is a sequence of commands separated by semicolon or new line.  File is the input file.  awk programs can be written in a file or given directly in the command line.  awk -f source-file input-file1 input-file2 …

41 A simple example $ awk –F”:” ‘/svln/ {print $1 “ “ $5}’ /etc/passwd –Prints login name and full name of svln from passwd file.  Suppose /etc/passwd file contains the following entries root:x:0:0::/root:/bin/bash svln:x:500:500:SVL Narasimham:/home/svln:/bin/bash guest:x:1000:1000::/home/guest:/bin/bash …  awk will see this file as follows  Each line is a record, and hence the number of records is the entries in the passwd file.  Field Separator is : (-F’:’)  Each record contains 7 fields separated by “:” and are denoted by $1 to $7  $0 Represents entire set of fields (record).

42 A simple example (cont..) Awk executable pattern to search Action to perform on line If pattern matches The file to operate upon Field Separator $ awk –F”:” ‘/svln/ {print $1 “ “ $5}’ /etc/passwd

43 Running awk programs  Running awk programs on Files $ awk 'program' input-file1 input-file2... where program consists of a series of patterns and actions.  Running awk programs on input from terminal $ awk 'program' ctrl-d  Running awk programs from files. $ awk -f source-file input-file1 input-file2... awk commands will be in source file.

44 awk Syntax  Awk follows C language.  The control structures are similar to C (if, for, and while)  Awk’s variables are stored internally as strings. x = “1.01” x = x + 1 print x The above will print the value 2.01  Comparison operators: "==", " ", " =", "!=“, "~" and "!~“. (“~” and “!~” operators mean "matches" and "does not match“).  Arithmetic operators: “+", “-", “/", “*“;  “^” is the exponentiation operator.  “%” is the modulo operator

45 awk Syntax  Arithmetic operators: “+", “-", “/", “*“, “%” (Modulo), ^ (Exponent)  C operators like “++”, “--”, “+=“, “-=”, “/=“ etc. are supported.  awk language supports associative one-dimensional arrays for storing strings or numbers.  Awk has two sections BEGIN and END which will be executed only once (before and after the awk command. These are used to initialize variables and use the data at the end of the process respectively. BEGIN{ x=0 }# executed before processing the file /^$/ { x=x+1 } # blank line count END { print "I found " x " blank lines. :)" } # executed at the end The above script calculates the number of blank lines. Note that BEGIN and END are special patterns.

46 Built-in Variables Some of the important variables are:  FIELDWIDTHS: Space separated list of columns, used for fixed width data. This overrides FS  FS: Input field separator. The value can be a single character string or a multi character regular expression. –F option sets it.  IGNORECASE: If this is non-zero, case is ignored.  OFS: Output field separator (default is space)  RS: Record separator (default is newline)  ARGC: Argument count  ARGV: Array of arguments ARGV[i] is i-th argument  FILENAME: Name of the file awk is currently reading  FNR: Current record number in the current file.  NF: Number of fields in the current record  NR: Number of input records awk processed since the begin of program execution

47 Awk examples $ awk 'BEGIN { RS = "/" } ; { print $0 }' file1.txt In this example the RS is modified to “/” from the default \n. $ awk '$1 ~ /abc/ { print $0 }' file.txt The pattern will print out all records from file file.txt whose first fields contain the string “abc”. $ awk '{ print $(2*2) }' file.txt Prints the 4 th field of each record.

48 awk Example  Finding average, Minimum and maximum of a set of numbers: Say the data is in a file called data.txt with the following numbers: 20 10 40 30 awk ‘ { if(min==”") {min=max=$1}; if($1>max) {max=$1}; if($1< min) {min=$1}; total+=$1; count+=1; } END {print total/count, min, max}’ data.txt

49 Shell Programming A group of commands have to be executed regularly they are stored in a file and executed as shell script or a shell program The above file should have execute permission Example #! /bin/bash #example.sh: sample program echo -n “Today is: ” ; date exit

50 Shell Variables  Shell variables are available to all shell programs and commands as environment variables. Some important variables are:  HOMEThe default argument (home directory) for the cd command.  PATHThe search path for commands  PS1Primary prompt string, by default ``$ ''.  PS2Secondary prompt string, by default ``> ''.  IFSInternal field separators, normally space, tab, and new-line.  SHELLShell name that is invoked  TERMStores the name of the terminal  User Defined variables  name=“Peter” (No gap on either side of = symbol)  export name  echo $name

51 Shell Variables  Special Shell Variables  Following are some of the shell variables, which can be used in a program The parameters are automatically set by the shell:  Variablemeaning  $nn th positional parameter ($0=command name, $1 = 1st argument,...)  $*Holds the entire list of arguments, excluding the command name, as a string  $@ Same as $* except when quoted as “$@” is “$1”, “$2”,.. where as “$*” is “$1 $2 $3...”.  $# Total number of positional parameters excluding the program name ($0)  $? Result of the last executed command.  $$ Process ID of the current shell.  $! Process ID of the last background command, invoked by & operator.  exit, exit 0,exit 1

52 The if condetional

53


Download ppt "Introduction to Linux. Topics Covered  History of  Unix  Linux  Windows  Features of Unix  Introduction to Open Source Software  Comparison of."

Similar presentations


Ads by Google