Unix - UNIX Shell Programming with Functions and Arguments
UNIX shell programming is a method of automating tasks by writing scripts that execute a series of commands. As shell scripts become larger and more complex, organizing code efficiently becomes essential. Functions and arguments are two important features that help make shell scripts modular, reusable, and easier to maintain. Functions allow a set of commands to be grouped under a single name, while arguments enable scripts and functions to receive input from users or other programs.
Understanding Functions in Shell Scripts
A function is a block of code designed to perform a specific task. Instead of writing the same commands multiple times, a function can be created and called whenever needed. This reduces code duplication and improves script readability.
The general syntax of a function in a shell script is:
function_name() {
commands
}
Alternatively:
function_name {
commands
}
Example:
greet() {
echo "Welcome to UNIX Shell Programming"
}
To execute the function:
greet
Output:
Welcome to UNIX Shell Programming
In this example, the function greet contains a simple message that is displayed whenever the function is called.
Advantages of Using Functions
Functions provide several benefits in shell programming:
-
Reduce repetition of code.
-
Improve script organization.
-
Simplify debugging and maintenance.
-
Allow code reuse in multiple places.
-
Make scripts easier to understand.
For large automation projects, functions help divide the script into smaller manageable sections.
Passing Arguments to Functions
Functions can accept input values known as arguments. These arguments are supplied when the function is called.
Example:
greet() {
echo "Hello, $1"
}
greet John
Output:
Hello, John
Here, $1 represents the first argument passed to the function.
Example with multiple arguments:
employee() {
echo "Name: $1"
echo "Department: $2"
}
employee Ravi Sales
Output:
Name: Ravi
Department: Sales
Arguments make functions flexible because the same function can work with different input values.
Special Argument Variables
Shell scripts provide special variables for handling arguments.
$0
Represents the script name.
Example:
echo $0
Output:
./script.sh
$1, $2, $3 ...
Represent the first, second, third, and subsequent arguments.
Example:
echo $1
echo $2
$#
Displays the total number of arguments passed.
Example:
echo $#
If three arguments are supplied:
./script.sh one two three
Output:
3
$@
Represents all arguments individually.
Example:
echo $@
Output:
one two three
$*
Represents all arguments as a single string.
Example:
echo $*
Output:
one two three
$$
Displays the process ID of the current script.
Example:
echo $$
Output might be:
2546
Returning Values from Functions
Shell functions do not return values in the same way as programming languages like C or Java. They typically return an exit status.
Example:
check() {
return 0
}
check
echo $?
Output:
0
A return value of 0 usually indicates success, while non-zero values indicate errors.
Example:
divide() {
if [ $2 -eq 0 ]
then
return 1
fi
return 0
}
divide 10 2
echo $?
Output:
0
Capturing Output from Functions
Functions can generate output using the echo command, which can then be stored in variables.
Example:
square() {
result=$(( $1 * $1 ))
echo $result
}
value=$(square 5)
echo $value
Output:
25
This technique is commonly used when calculations or data processing are required.
Local and Global Variables
Variables defined inside functions are generally global unless declared as local.
Example:
name="UNIX"
display() {
echo $name
}
display
Output:
UNIX
To limit a variable's scope to a function:
display() {
local name="Shell"
echo $name
}
The variable exists only within the function.
Benefits of local variables include:
-
Prevent accidental modification of global data.
-
Improve code reliability.
-
Make debugging easier.
Command-Line Arguments in Shell Scripts
Arguments can also be passed directly to a script.
Example script:
#!/bin/sh
echo "First Argument: $1"
echo "Second Argument: $2"
Execution:
./script.sh Apple Mango
Output:
First Argument: Apple
Second Argument: Mango
Command-line arguments allow users to provide input without modifying the script.
Argument Validation
Scripts should verify that required arguments are supplied.
Example:
if [ $# -lt 2 ]
then
echo "Usage: script.sh arg1 arg2"
exit 1
fi
This ensures the script receives the necessary input before proceeding.
Practical Example
The following script demonstrates functions and arguments together:
#!/bin/sh
addition() {
sum=$(( $1 + $2 ))
echo "Sum: $sum"
}
subtraction() {
diff=$(( $1 - $2 ))
echo "Difference: $diff"
}
addition 20 10
subtraction 20 10
Output:
Sum: 30
Difference: 10
The script contains two separate functions, each performing a specific task. Arguments are passed to the functions when they are called.
Best Practices for Using Functions and Arguments
-
Create small functions that perform one specific task.
-
Use meaningful function names.
-
Validate input arguments before processing.
-
Use local variables whenever possible.
-
Avoid excessive nesting of functions.
-
Add comments to improve readability.
-
Reuse functions instead of duplicating code.
-
Test functions independently before integrating them into larger scripts.
Conclusion
Functions and arguments are fundamental building blocks of UNIX shell programming. Functions help organize scripts into reusable modules, while arguments enable dynamic interaction with users and other programs. Together, they make shell scripts more efficient, maintainable, and scalable. Understanding how to define functions, pass arguments, handle return values, and validate inputs is essential for developing professional UNIX automation scripts and system administration tools.