Parameter Passing
Understanding Variables and Parameters in the Shell
In the shell, variables are used to store values that can be referenced later in a script or command. Parameters, a subset of variables, are values passed to commands or scripts. They enable dynamic behavior by allowing commands to accept input from the user or external sources.
Basic Concepts
Parameters are values that are passed to a command or script. They can be positional (determined by their position on the command line) or named (specified with a -- option). Positional parameters are accessed via $1, $2, etc., while named parameters are assigned using --option=value.
For example:
ls -l --help
Here, --help is a named parameter, and ls is the command. The output includes help information based on the named parameter.
Passing Parameters
Parameters are passed to commands in two primary ways:
Positional Parameters: These are determined by the order in which arguments are provided.
Example:
echo "$1 $2"If called with
./script.sh hello world, this outputshello world.
Named Parameters: These are specified with
--followed by a name and value.Example:
grep --file=logfile.txt --line=5This searches for lines 5 in
logfile.txt.
Commands can accept both types of parameters. For instance, grep can use positional arguments for file names and named arguments for line numbers.
Advanced Techniques
Parameter expansion allows manipulation of values. For example:
${VAR#*}removes the first occurrence of*fromVAR.${VAR%%.*}removes the last occurrence of*fromVAR.
Handling optional parameters involves default values. For example:
find . -type f -name "*.txt" --print --time=lastmod=24h
Here, --time=lastmod=24h is a named parameter with a default value if not specified.
Examples
A script using both positional and named parameters:
#!/bin/bash
echo "File: ${1:-default.txt}"
echo "Line: ${2:-5}"
If called with ./script.sh file.txt 3, it outputs:
File: file.txt
Line: 3
This demonstrates how positional and named parameters can be combined.
Conclusion
Parameter passing in the shell enables flexibility by allowing commands to accept dynamic inputs. Understanding positional and named parameters, along with advanced techniques like expansion and defaults, is essential for writing efficient scripts. Mastery of these concepts allows for powerful automation and customization.