Problem Statement
How do you define a function in bash?
Explanation
Function definition: function name() { commands; } or simply name() { commands; }. Both forms equivalent. Example:
```bash
function greet() {
echo "Hello, $1"
}
# or
greet() {
echo "Hello, $1"
}
```
Call with arguments: greet "World" outputs "Hello, World".
Function arguments: $1, $2, etc. are function parameters, not script parameters. $@ and $# work within function scope. Local variables: local VAR=value creates variable local to function, preventing modification of global scope. Return status with return N (0-255), or use echo for return values: RESULT=$(function_name).
Functions can call other functions, including recursively. Define functions before calling them in script. Organize related commands into functions for reusability. Example:
```bash
check_file() {
local file=$1
if [ -f "$file" ]; then
return 0
else
return 1
fi
}
if check_file "test.txt"; then
echo "File exists"
fi
```
Functions improve code organization, enable code reuse, make scripts more maintainable, and allow testing individual components. Understanding functions is essential for writing modular, professional scripts.
