Presentation is loading. Please wait.

Presentation is loading. Please wait.

Positional Parameters $# The number of positional parameters $* The list of positional parameters $0 The name of the command $1 The first argument to the.

Similar presentations


Presentation on theme: "Positional Parameters $# The number of positional parameters $* The list of positional parameters $0 The name of the command $1 The first argument to the."— Presentation transcript:

1 Positional Parameters $# The number of positional parameters $* The list of positional parameters $0 The name of the command $1 The first argument to the command $2 The second argument to the command

2 Positional Parameters echo The name of the command is $0 echo The arguments are $* echo The number of arguments are $# echo The first argument is $1

3 The set command We can make set take the values to be assigned to positional parameters set firstname lastname echo $2 $1 echo date : Prints date echo `date` : Due to the backquotes, the output of the date command is printed which is something like Tue Jun 21 10:23:36 PDT 2010 set `date` echo $1 \\ output = Tue

4 Conditional Parameter Substitution ${variable-word} If the variable exists, then this expression returns the value of the variable. If the variable does not exist, it returns the value specified by word. animal=tiger echo ${animal-lion} displays tiger echo $bird displays nothing echo ${bird-eagle} displays eagle echo $bird displays nothing

5 Conditional Parameter Substitution ${variable=word} If the variable exists, then this expression returns the value of the variable. If the variable does not exist, it returns the value specified by word and assigns the value of the variable as word. animal=tiger echo ${animal=lion} displays tiger echo $bird displays nothing echo ${bird=eagle} displays eagle echo $bird displays eagle

6 Conditional Parameter Substitution ${variable+word} If the variable exists, then this expression returns the value of word. If the variable does not exist, it returns no value. animal=tiger echo ${animal+lion} displays lion echo $bird displays nothing echo ${bird+eagle} displays nothing

7 Conditional Parameter Substitution ${variable?message} If the variable exists, then this expression returns the value of the variable. If the variable does not exist, it prints the message.

8 Positional Parameters $# The number of positional parameters $* The list of positional parameters $0 The name of the command $1 The first argument to the command $2 The second argument to the command $@ The same as $*, unless used in double quotes “$*” expands to a single string containing arguments “$@” expands to individual arguments in strings $? The exit status of the last executed command $$ The process number (PID) of the current shell $! The process number of the last background shell

9 Shift We have used the set command to set upto 9 words. Eg: $ set You have the capacity to learn from mistakes. You will learn a lot in your life. $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 You have the capacity to learn from mistakes. You You0 You1 $ shift 7 $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 mistakes. You will learn a lot in your life. First seven words have shifted out. Each word vacated a position for the one on its right with the first word getting lost

10 Shift abc def pqr xyz $0 $1 $2 $3 $* refers to $1 $2 $3 var=$1 shift $1 is now pqr $2 is xyz

11 tr (Translating characters) command The tr (translate) command can work on individual characters in a file. It Translate, squeeze, and/or delete characters from standard input, writing to standard output. syntax: tr [option(s)] expression1 [expression2] [ standard-input] It takes two expressions as input. It translates each character of the first expression with its counterpart in the second expression.

12 e.g. consider the book.lst file as follow: b001 | Let us C | 12/03/90 b002 | Visual Basic in 21 days | 12/08/91 b003 | Data structure through C | 04/12/90 Suppose we wish to translate all | in out book.lst file with ‘,’ and all / with ‘-‘, then we have to give the following command: $tr ‘|/’ ‘,-‘ < book.lst or$cat book.lst | tr ‘|/’ ‘,-‘ Note that the two expressions are given in single quotes. Note that the lengths of the two expressions should be equal.

13 tr can also work on ranges in the expression list. For example, to convert all the lowercase letters in book.lst file to uppercase, we can give a tr command as follows: $tr ‘[a-z]’ ‘[A-Z]’ $tr [:lower:] [:upper:] Options (1) –d (delete) : It delete characters in expression1, do not translate e.g. $tr -d ‘|’ echo "my username is 432234" | tr -d [:digit:] –s (squeeze/compress) : compressing multiple consecutive characters e.g. $tr –s ‘ ‘ < file1 – it removes multiple spaces.

14 –c (complement) : Complementing the expression The –c option complements the set of characters in the expression. (i) tr –cd ‘[a-zA-Z]’ < file1 : It deletes all characters other than alphabets. (ii) echo “BSc IT 001" | tr –c '[a-zA-Z]' '*' : it replaces all characters other then alphabets with '*'.

15 Control statements Without control statements, execution within a shell scripts flows from one statement to the next in succession. Control statements control the flow of execution in a programming language.

16 Control statements The three most common types of control statements: ◦ conditionals: if/then/else, case,... ◦ loop statements: while, for, until, do,... ◦ branch statements: subroutine calls (good programming practice), goto (usage not recommended).

17 for loops for loops allow the repetition of a command for a specific set of values. Syntax: for var in value1 value2... do command_set done ◦ command_set is executed with each value of var (value1, value2,...) in sequence

18 for for a in abc def pqr xyz do echo a is $a done Can also be written as for a in abc def pqr xyz ; do echo a is $a; done

19 for for a in $* do echo The argument is $a done for a is the same as for a in $*

20 for # command for concatenating all files in first one # concatenate file1 file2 file3 mainfile=$1 shift for filename do cat $filename >> $mainfile done

21 for for filename in * do echo The name of the file is $filename done echo What are your names\? read mnames for m in mnames do echo $m done

22 The if command Simple form: if decision_command_1 then command_set_1 fi

23 The if command Importance of having then on the next line: ◦ Each line of a shell script is treated as one command. ◦ then is a command in itself  Even though it is part of the if structure, it is treated separately.

24 if if condition then statements fi if condition then statements else statements fi if condition then statements elif condition then statements elif condition then statements else statements fi

25 CASE case value in choice1) commands ;; choice2) commands ;; esac

26 case Case first matches the expression. If the match succeeds, then it executes commands1, which may be one or more commands. When a match is found, the shell executes all commands in that case upto ;; and entire construct is closed with esac

27 case echo Enter one of your choices echo 1 date echo 2 who echo 3 ps read ch case $ch in 1) man date ;; 2) man who ;; 3) man ps ;; *) echo Not in our list esac

28 case echo Enter one of your choices echo d date echo w who echo p ps read ch case $ch in d) man date ;; w) man who ;; p) man ps ;; *) echo Not in our list esac

29 case echo Enter one of your choices echo date echo who echo ps read ch case $ch in date) man date ;; who) man who ;; ps) man ps ;; *) echo Not in our list esac

30 case echo Enter one of your choices echo date who ps ls dir read ch case $ch in date) man date ;; who) man who ;; ps) man ps ;; dir | ls) man ls ;; *) echo Not in our list esac

31 case echo Enter one of your choices echo date who ps ls dir read ch case $ch in date) man date ;; who) man who ;; ps) man ps ;; dir | ls) man ls ;; [aA]*) echo A command starting with a ;; *) echo Not in our list esac

32 The while loop While loops repeat statements as long as the next Unix command is successful. Works similar to the while loop in C.

33 #! /bin/bash i=1 sum=0 while [ $i -le 100 ] do sum=`expr $sum + $i` i=`expr $i + 1` done echo The sum is $sum. NOTE: The value of i is tested in the while to see if it is less than or equal to 100.

34 The until loop Until loops repeat statements until the next Unix command is successful. Works similar to the do-while loop in C.

35 #! /bin/bash x=1 until [ $x -gt 3 ] do echo x = $x x=`expr $x + 1` done NOTE: The value of x is tested in the until to see if it is greater than 3.

36 The test command This command investigates the sort of tests and help in deciding whether to execute the commands in the if block or the else block Use for checking validity. Three kinds: ◦ Check on files ◦ Check on strings ◦ Check on integers

37 Testing on files ◦ test –f file: True if the file exist and is not a directory ◦ test -d file: True if the file exist and is a directory ◦ test –r file: True if the file exist and is readable ◦ test –w file: True if the file exist and is writable ◦ test –x file: True if the file exist and is executable ◦ test –s file: True if the file exist and has a size greater than 0

38 Testing on strings ◦ test string1 = string2: True if the strings are same ◦ test string1 != string2: True if the strings are different ◦ test -n string: True if the length of the string is greater than 0 ◦ test –z string: True if the length of the string is zero

39 Testing on integers ◦ test n1 –eq n2: True if the numbers are equal ◦ test n1 –ne n2: True if the numbers are not equal ◦ test n1 –lt n2: True if n1 is less than n2 ◦ test n1 –gt n2:True if n1 is greater than n2 ◦ test n1 –le n2: True if n1 is less than or equal to n2 ◦ test n1 –ge n2: True if n1 is greater than or equal to n2

40 test ! Negates the expression test ! –w filename # returns true if the file is not writable -a Binary and -o Binary or test –r filename –a –w filename # returns true if the file is readable and writable test \( -r fname –a –w fname \) –o \( -r fname1 –a –w fname1 \)

41 The test command has an alias ‘[]’. ◦ Each bracket must be surrounded by spaces #!/bin/bash smallest=10000 for i in 5 8 19 8 7 3 do if [ $i -lt $smallest ] then smallest=$i fi done echo $smallest

42 test animal=tiger test $animal = tiger echo $? # displays 0 test $animal = lion echo $? # displays 1

43 test echo Name the best operating system read opsys until test $opsys = unix do echo Your answer is wrong echo Name the best operating system read opsys done

44 expr expr command is capable of evaluating an arithmetic operations, as well as modulus function a=20 b=10 echo `expr $a + $b` echo `expr $a - $b` echo `expr $a \* $b` echo `expr $a / $b` echo `expr $a % $b`

45 let Korn and bash came up with a built-in integer handling facility that totally dispenses with the need to use expr. let sum=256+128 echo $sum let x=12 y=18 z=5 let z=x+y+z echo $z Since let get rid of $ altogether when making an assignment and is much faster than expr

46 eval The eval utility is used to perform variable indirection The eval command evaluates the command line to complete any shell substitutions necessary and then executes the command. This is needed when a single pass of shell substitution does not complete all the needed expansions Eg: abc=10 x=abc y='$'$x echo $y \\ output = $abc eval y='$'$x echo $y \\ output = 10

47 Eg. display the last argument supplied from the command line eval echo '$'$# Eg. eval is also useful in assigning value to a variable using another variable echo "Enter a and b" read a b echo Assigning the value $b to variable $a eval $a=$b # print the value eval echo '$'$a

48 exec exec is useful in replacing the current shell with another one. When you use exec ksh, the current shell's environment is completely replaced by the new shell This feature also lets you log into different user account by using exec login userid. This technique is useful when working on remote machines with telnet.

49 Exec – Redirecting the standard stream It can redirect the standard streams for an entire script. If script has several commands whose standard output go to a single file, the instead of using separate redirection symbols for each, you can use exec to reassign their default destination Eg: exec > found.lst

50 echo "enter filename :\c" read fname terminal='/dev/tty' exec < $fname while read line do echo $line done exec < $terminal read input echo $input

51 exec < $fname ensures that the input for the read statement now comes from the file and not from the keyboard Once the while loop is terminated, using the value stored in terminal the standard input is reset back to original

52 Functions Functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their individual task when it is needed. Using functions to perform repetitive tasks is an excellent way to create code reuse.

53 Creating Functions: To declare a function, simply use the following syntax: function_name () { list of commands } Eg: # Define your function here Hello () { echo "Hello World" } # Invoke your function Hello

54 Pass Parameters to a Function: You can define a function which would accept parameters while calling those function. These parameters would be represented by $1, $2 and so on. Eg. Hello () { echo "Hello World $1 $2" } # Invoke your function Hello John Mark // output : Hello World John Mark

55 A link is a pointer to a file. In fact, in UNIX all filenames are just links to a file. Most files only have one link. -rw-r--r-- 1 root root 154 Feb 4 15:00 letter3 -rw-r--r-- 1 root root 64 Feb 4 15:00 names drwxr-xr-x 2 root root 512 Feb 4 15:00 Program Additional links to a file allow the file to be shared. The ln command creates new links. $ ln names NAMES $ ls –l -rw-r--r-- 2 root root 64 Feb 6 18:36 NAMES -rw-r--r-- 1 root root 154 Feb 4 15:00 letter3 -rw-r--r-- 2 root root 64 Feb 4 15:00 names drwxr-xr-x 2 root root 512 Feb 4 15:00 Program Links

56 ln creates a new link, not a new file. The new link and the original filename are equivalent pointers to the file. The last argument is the link destination, and can be:  A pathname of a new regular file $ ln names NAMES  No second argument (same as giving a second argument of “.”) $ ln Program/p1

57 A link has two pieces of information  A name  An inode number An inode number is an index into a system table that has all the information about the file (e.g., owner, size). $ ln names NAMES root NAMESnamesletter3 007 Golden Eye Tomorrow Never Dies inode: 42979 user: 4501 group: 1501 address:... system table file contents

58 You can use ls -i to see if two links point to the same inode: $ ls -li 42979 -rw-r--r-- 2 root root 64 Feb 6 18:36 NAMES 42976 -rw-r--r-- 1 root root 34 Feb 4 15:00 letter3 42979 -rw-r--r-- 2 root root 64 Feb 4 15:00 names 59980 drwxr-xr-x 2 root root 512 Feb 4 17:10 Program So, using rm actually only removes a link. When the last link to a file is removed, the operating system actually removes the file.

59 SYMBOLIC LINKS : A symbolic link is a pointer to a pathname, not a pointer to the file itself.  ln -s original target creates a symbolic link.  A symbolic link is not equivalent to a hard link. The symbolic link has a different inode. $ ln -s names snames $ ls -li 42979 -rw-r--r-- 3 root root 64 Feb 6 18:36 NAMES 42976 -rw-r--r-- 1 root root 34 Feb 4 15:00 letter3 42979 -rw-r--r-- 3 root root 64 Feb 4 15:00 names 59980 drwxr-xr-x 2 root root 512 Feb 4 17:10 Program 42916 lrwxrwxrwx 1 root root 5 Feb 8 17:09 snames -> names Symbolic links are sometimes called soft links, and “regular” links are sometimes called hard links.

60 You can’t make a hard link to a directory, but you can make a symbolic link to a directory. $ ln Program ProgramLink ln: ‘Program’ : hardlink not allowed for directory $ ln -s Program ProgramLink $ ls -li 42979 -rw-r--r-- 3 root root 64 Feb 6 18:36 NAMES 42976 -rw-r--r-- 1 root root 34 Feb 4 15:00 letter3 42979 -rw-r--r-- 3 root root 64 Feb 4 15:00 names 59980 drwxr-xr-x 2 root root 512 Feb 4 17:10 Program/ 42917 lrwxrwxrwx 1 root root 6 Feb 8 17:21 ProgramLink -> Program/ 42916 lrwxrwxrwx 1 root root 5 Feb 8 17:09 snames -> names $ cd ProgramLink $ pwd /homes/root/Program DIFFERENCE BETWEEN HARD AND SOFT LINKS

61 You can also make symbolic links across file systems. $ pwd /homes/root/secret $ ls -l /tmp -rw-rw-r-- 1 root sys 13636 Feb 2 01:41 ps_data $ ln /tmp/ps_data ps_data ln: ps_data is on a different file system $ ln -s /tmp/ps_data ps_data $ ls -li total 4 59944 -rw-r--r-- 1 root root 154 Feb 4 16:38 letter1 59597 lrwxrwxrwx 1 root root 12 Feb 8 17:39 ps_data -> /tmp/ps_data There is no way to tell how many symbolic links there are to a file.

62 The most important difference between hard and symbolic links occur when a link is removed.  For a hard link: $ echo 123 > first $ ln first second $ rm first $ cat second 123 $ echo 456 > first $ cat first 456 $ cat second 123

63  For a symbolic link: $ echo 123 > first $ ln -s first second $ rm first $ cat second cat: cannot open second $ echo 456 > first $ cat first 456 $ cat second 456

64 Summarizing : 1.Soft Links: Soft Links can be created across file systems. Soft link has a different inode number than the original file. On deleting the original file, soft link cannot be accessed. Soft link needs extra memory to store the original file name as its data. Source file need not exist for soft link creation. Can be created on a file or on a directory. Access to the file is slower due to the overhead to access file. 2. Hard Links: Hard links can be created only within the file system. Hard links have the same inode number as the original file. On deleting the original file, hard linked file can still be accessed. Hard links do not need any extra data memory to save since it uses links Source file should exist. Can be created only on files, not on directories. Access to the file is faster compared to soft link.


Download ppt "Positional Parameters $# The number of positional parameters $* The list of positional parameters $0 The name of the command $1 The first argument to the."

Similar presentations


Ads by Google