Table of Contents for
Learning Linux Shell Scripting

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Learning Linux Shell Scripting by Ganesh Sanjiv Naik Published by Packt Publishing, 2015
  1. Cover
  2. Table of Contents
  3. Learning Linux Shell Scripting
  4. Learning Linux Shell Scripting
  5. Credits
  6. About the Author
  7. Acknowledgments
  8. About the Reviewers
  9. www.PacktPub.com
  10. Preface
  11. What you need for this book
  12. Who this book is for
  13. Conventions
  14. Reader feedback
  15. Customer support
  16. 1. Getting Started and Working with Shell Scripting
  17. Tasks done by shell
  18. Working in shell
  19. Learning basic Linux commands
  20. Our first script – Hello World
  21. Compiler and interpreter – difference in process
  22. When not to use scripts
  23. Various directories
  24. Working more effectively with shell – basic commands
  25. Working with permissions
  26. Summary
  27. 2. Drilling Deep into Process Management, Job Control, and Automation
  28. Monitoring processes using ps
  29. Process management
  30. Process monitoring tools – top, iostat, and vmstat
  31. Understanding "at"
  32. Understanding "crontab"
  33. Summary
  34. 3. Using Text Processing and Filters in Your Scripts
  35. IO redirection
  36. Pattern matching with the vi editor
  37. Pattern searching using grep
  38. Summary
  39. 4. Working with Commands
  40. Command substitution
  41. Command separators
  42. Logical operators
  43. Pipes
  44. Summary
  45. 5. Exploring Expressions and Variables
  46. Working with environment variables
  47. Working with read-only variables
  48. Working with command line arguments (special variables, set and shift, getopt)
  49. Understanding getopts
  50. Understanding default parameters
  51. Working with arrays
  52. Summary
  53. 6. Neat Tricks with Shell Scripting
  54. The here document and the << operator
  55. The here string and the <<< operator
  56. File handling
  57. Debugging
  58. Summary
  59. 7. Performing Arithmetic Operations in Shell Scripts
  60. Using the let command for arithmetic
  61. Using the expr command for arithmetic
  62. Binary, octal, and hex arithmetic operations
  63. A floating-point arithmetic
  64. Summary
  65. 8. Automating Decision Making in Scripts
  66. Understanding the test command
  67. Conditional constructs – if else
  68. Switching case
  69. Implementing simple menus with select
  70. Looping with the for command
  71. Exiting from the current loop iteration with the continue command
  72. Exiting from a loop with a break
  73. Working with the do while loop
  74. Using until
  75. Piping the output of a loop to a Linux command
  76. Running loops in the background
  77. The IFS and loops
  78. Summary
  79. 9. Working with Functions
  80. Passing arguments or parameters to functions
  81. Sharing the data by many functions
  82. Declaring local variables in functions
  83. Returning information from functions
  84. Running functions in the background
  85. Creating a library of functions
  86. Summary
  87. 10. Using Advanced Functionality in Scripts
  88. Using the trap command
  89. Ignoring signals
  90. Using traps in function
  91. Running scripts or processes even if the user logs out
  92. Creating dialog boxes with the dialog utility
  93. Summary
  94. 11. System Startup and Customizing a Linux System
  95. User initialization scripts
  96. Summary
  97. 12. Pattern Matching and Regular Expressions with sed and awk
  98. sed – noninteractive stream editor
  99. Using awk
  100. Summary
  101. Index

Chapter 9. Working with Functions

In the last chapter, you learned about using decision making in scripts by working with test, if-else, and switch case. We also used select for loop with menu. For repeated tasks, such as processing lists, you learned to use the for and while loops and the do while. You also learned about how to control loops using the break and continue statements.

In this chapter, you will learn the following topics:

  • Writing a new function and calling
  • Sharing data between functions
  • Passing parameters to functions
  • Creating a library of functions

Understanding functions

We, human beings, in our day-to day lives, take help from people, who are specialized in certain knowledge or skills, such as doctors, lawyers, and barbers. This helps our lives to be more organized and comfortable so that we need not learn every skill in this world. We take advantage of skills that have already been acquired by other people. The same thing applies to software development as well. If we use whatever code or scripts that have already been developed, then this will save our time and energy.

In real-world scripts, we break down big tasks or scripts into smaller logical tasks. This modularization of scripts helps in the better development and understanding of code. The smaller logical blocks of script are be called functions.

The advantages of functions are as follows:

  • If the script is very big, then understanding it becomes very difficult. Using functions, we can easily understand complex script through logical blocks or functions.
  • When a big and complex script is divided into functions, then it becomes easy to develop and test the script.
  • If a certain part of code is repeated again and again in the big script, then using functions to replace repetitive code is very practical, such as checking whether the file or directory is present or not.
  • We define functions for specific tasks or activities. Such functions can be called as commands in scripts.

Functions can be defined on a command line or inside scripts. The syntax for defining functions on a command line is as follows:

functionName { command_1; command_2; . . . }

Or:

functionName() { command_1; command_2; . . }

In single-line functions, every command should end with a semicolon.

Let's write a very simple function to illustrate the preceding syntax:

$ hello() {echo 'Hello world!';}

We can use the previously defined function as follows:

$ hello

Output:

Hello world!

The syntax of the function declaration inside the Shell script is as follows:

function_name() {
   block of code
}

An alternate function syntax is mentioned here:

function function_name
{
   block of code
}

Functions should be defined at the beginning of a script.

We can add this function in the Shell script function_01.sh as follows:

#!/bin/bash
hello()
{echo "Executing function hello"
}
echo "Script has started now"
hello
echo "Script will end"

Test the script as follows:

$ chmod +x function_01.sh
$ ./function_01.sh

Output:

Script has started now
Executing function hello
Script will end

We can modify the preceding script into function_02.sh with some more functionality, shown as follows:

#!/bin/bash
function greet()
{ echo "Hello $LOGNAME, today is $(date)"; }
greet

Test the script as follows:

$ chmod +x function_02.sh
$ ./function_02.sh

Output:

Hello ganesh, today is Sun Jul  5 22:47:23 PDT 2015

The system init functions are placed in the /lib/lsb/init-functions folder in the Linux operating system:

The script function_03.sh with a function for listing the present working directory and listing all the files in the current directory is as follows:

#!/bin/bash
function_lister ()
{
   echo Your present working directory is `pwd`
   echo Your files are:
   ls
}
function_lister

Test the script as follows:

$ chmod +x function_03.sh
$ ./function_03.sh

Output:

Your present working directory is /home/student/Desktop/test
Your files are:
01.sh  02.sh  03.sh

The script function_04.sh with a function to pause the script until users press any key is as follows:

#!/bin/bash
# pause: causes a script to take a break
pause()
{
echo "To continue, hit RETURN."
read q
}
pause

Test the script as follows:

$ chmod +x function_04.sh
$ ./function_04.sh

Output:

To continue,   hit  RETURN.
(after hitting any key it resumes)

The script function_05.sh with a function to print the previous day is as follows:

#!/bin/bash
yesterday()
{
date --date='1 day ago'
}
yesterday

Test the script as follows:

$ chmod +x function_05.sh
$ ./function_05.sh

Output:

Sat Jul  4 22:52:24 PDT 2015

The function to convert lowercase letters into uppercase letters is shown in function_06.sh as follows:

#!/bin/bash
function Convert_Upper()
{
echo $1 | tr 'abcdefghijklmnopqrstuvwxyz' \
               'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
}
Convert_Upper "ganesh naik - embedded android and linux training"

Test the script as follows:

$ chmod +x function_06.sh
$ ./function_06.sh

Output:

GANESH NAIK - EMBEDDED ANDROID AND LINUX TRAINING

Displaying functions

If you want to see all the declared functions in the shell environment, then enter the following command:

$ declare -f

If you want to see a particular function, then here is the command:

$ declare -f hello

Output:

hello ()
{
    echo 'Hello world!'
}

Removing functions

If we no longer need the function in shell, then we use following command:

$ unset -f hello
$ declare -f# Check the function in shell environment.

Output:

Nothing will be displayed on the screen, as the function hello is removed from the shell environment with the unset command.