Unit – III: Linux Scripting
1. Creating Functions
Functions in shell scripting allow reusability, modular programming, and structured script
development.
They help avoid code duplication and improve readability.
Basic Script Functions
A function is a block of reusable code. In shell, it can be defined in two ways:
1) function name { commands }
2) name() { commands }
Example:
myfunc() {
echo "Hello, this is a function"
}
myfunc
Returning a Value
Functions can return a value using the return command or by echoing output.
The return command gives an exit status (0–255), while echo can be captured with
command substitution.
Using Variables in Functions
Variables inside functions can be local or global. By default, variables are global.
The 'local' keyword restricts scope to within the function.
Array and Variable Functions
Functions can accept arguments like $1, $2, etc., and arrays can be passed using quoting.
Function Recursion
A function can call itself recursively to perform repeated tasks until a condition is met.
Creating a Library
Frequently used functions can be stored in a separate file (library) and sourced into scripts
using:
. filename OR source filename
Using Functions on the Command Line
Functions can be declared and used directly in the interactive shell for quick tasks.
2. Writing Scripts for Graphical Desktops
Creating Text Menus
Text menus provide interactive options to users. They can be built using case or select
statements.
Example (using case):
while true
do
echo "1. Date"
echo "2. Current Directory"
echo "3. Exit"
read choice
case $choice in
1) date ;;
2) pwd ;;
3) break ;;
esac
done
Building Text Window Widgets
Text window widgets can be created using tools like 'dialog' or 'whiptail' to add GUI-like
menus in terminal.
Example with dialog:
dialog --menu "Choose an option" 15 40 3 1 "Date" 2 "List Files" 3 "Exit"
Adding X Window Graphics
Scripts can launch X Window GUI applications using commands like xterm, zenity, or
kdialog.
Example:
zenity --info --text="Hello from Linux Script!"
3. Introducing sed and gawk
Learning about the sed Editor
sed (Stream Editor) is used for text manipulation in a non-interactive way. It reads input
line by line, applies operations, and writes the result.
Example: sed 's/Linux/Unix/' [Link]
Getting Introduced to the gawk Editor
gawk (GNU awk) is a text-processing language used for pattern scanning and data
extraction.
Example: echo "Linux Scripting" | gawk '{print $2}'
Exploring sed Editor Basics
Basic sed commands include:
- Substitution (s)
- Deletion (d)
- Printing (p)
Example:
sed -n '1,3p' [Link] # Print lines 1 to 3