ult/Section_5.rst
changeset 59 8c15077f028d
parent 56 eee394eb05fc
child 60 8a36825e21c5
equal deleted inserted replaced
58:88ab79104a62 59:8c15077f028d
   605   until false
   605   until false
   606   do
   606   do
   607     echo "True"
   607     echo "True"
   608   done
   608   done
   609 
   609 
       
   610 Functions
       
   611 ---------
       
   612 
       
   613 When a group of commands are repeatedly being used within a script, it is convenient to group them as a function. This saves a lot of time and you can avoid retyping the code again and again. Also, it will help you maintain your code easily. Let's see how we can define a simple function, ``hello-world``. Functions can be defined in bash, either using the ``function`` built-in followed by the function name or just the function name followed by a pair of parentheses. 
       
   614 ::
       
   615 
       
   616   function hello-world
       
   617   { 
       
   618   echo "Hello, World."; 
       
   619   }
       
   620 
       
   621   hello-world () {
       
   622     echo "Hello, World.";
       
   623   }
       
   624 
       
   625   $ hello-world
       
   626   Hello, World.
       
   627 
       
   628 Passing parameters to functions is similar to passing them to scripts. 
       
   629 ::
       
   630 
       
   631   function hello-name
       
   632   { 
       
   633   echo "Hello, $1."; 
       
   634   }
       
   635 
       
   636   $ hello-name 9
       
   637   Hello, 9.
       
   638 
       
   639 Any variables that you define within a function, will be added to the global namespace. If you wish to define variables that are restricted to the scope of the function, define a variable using the ``local`` built-in command of bash.
       
   640 
       
   641 We shall now write a function for the word frequency generating script that we had looked at in the previous session. 
       
   642 
       
   643 ::
       
   644 
       
   645   function word_frequency {
       
   646     if [ $# -ne 1 ]
       
   647     then
       
   648       echo "Usage: $0 file_name"
       
   649       exit 1
       
   650     else 
       
   651       if [ -f "$1" ]
       
   652       then
       
   653         grep  "[A-Za-z]*" -o "$1" | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr | less
       
   654       fi
       
   655     fi
       
   656   }
       
   657 
       
   658 As an exercise, modify the function to accept the input for the number of top frequency words to be shown (if none is given, assume 10).
       
   659 
   610 
   660 
   611 Further Reading:
   661 Further Reading:
   612 ---------------- 
   662 ---------------- 
   613 	* http://www.freeos.com/guides/lsst/ 
   663 	* http://www.freeos.com/guides/lsst/ 
   614 	* http://www.freeos.com/guides/lsst/ch02sec01.html
   664 	* http://www.freeos.com/guides/lsst/ch02sec01.html