乐闻世界logo
搜索文章和话题

How to define and call functions in Shell scripts? How to pass parameters and return values?

3月6日 21:33

Function definition, calling, and parameter passing mechanisms in Shell scripts are as follows:

Function Definition

Basic Syntax

bash
function_name() { commands } # Or use the function keyword function function_name { commands }

Function Definition Examples

bash
# Simple function greet() { echo "Hello, World!" } # Function with parameters greet_user() { echo "Hello, $1!" } # Function with multiple parameters add() { local sum=$(($1 + $2)) echo "Sum: $sum" } # Function with default values backup_file() { local file=${1:-"default.txt"} local backup_dir=${2:-"./backup"} echo "Backing up $file to $backup_dir" }

Function Calling

Basic Call

bash
# Define function greet() { echo "Hello, World!" } # Call function greet # Output: Hello, World!

Passing Parameters

bash
# Define function with parameters greet_user() { echo "Hello, $1!" } # Call and pass parameters greet_user "John" # Output: Hello, John! # Pass multiple parameters add() { echo "$1 + $2 = $(($1 + $2))" } add 5 3 # Output: 5 + 3 = 8

Function Parameters

Positional Parameters

bash
show_args() { echo "First argument: $1" echo "Second argument: $2" echo "Third argument: $3" echo "All arguments: $@" echo "Number of arguments: $#" } show_args "apple" "banana" "cherry" # Output: # First argument: apple # Second argument: banana # Third argument: cherry # All arguments: apple banana cherry # Number of arguments: 3

Handling Variable Parameters

bash
# Handle any number of parameters sum_all() { local total=0 for num in "$@"; do total=$((total + num)) done echo "Total: $total" } sum_all 1 2 3 4 5 # Output: Total: 15

Local Variables

local Keyword

bash
# Use local to declare local variables counter=0 increment() { local counter=10 echo "Inside function: $counter" counter=$((counter + 1)) echo "After increment: $counter" } increment echo "Outside function: $counter" # Output: # Inside function: 10 # After increment: 11 # Outside function: 0

Importance of Local Variables

bash
# Not using local causes global variables to be modified global_var="original" bad_function() { global_var="modified" } good_function() { local global_var="local only" echo "Local: $global_var" } bad_function echo "After bad_function: $global_var" # Output: After bad_function: modified good_function echo "After good_function: $global_var" # Output: After good_function: modified

Return Values

Using return for Status Codes

bash
check_file() { if [ -f "$1" ]; then return 0 # Success else return 1 # Failure fi } check_file "/etc/passwd" if [ $? -eq 0 ]; then echo "File exists" else echo "File does not exist" fi

Using echo for Return Values

bash
# Return strings or calculation results get_username() { echo "John Doe" } username=$(get_username) echo "Username: $username" # Output: Username: John Doe # Return calculation result calculate() { echo $(($1 * $2)) } result=$(calculate 5 4) echo "Result: $result" # Output: Result: 20

Returning Arrays

bash
get_array() { local arr=("apple" "banana" "cherry") echo "${arr[@]}" } fruits=($(get_array)) for fruit in "${fruits[@]}"; do echo "Fruit: $fruit" done

Function Libraries and Import

Creating Function Library

bash
# File: mylib.sh #!/bin/bash log_info() { echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1" } log_error() { echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $1" >&2 } check_command() { if command -v "$1" >/dev/null 2>&1; then return 0 else return 1 fi }

Importing Function Library

bash
#!/bin/bash # Import function library source ./mylib.sh # Or . ./mylib.sh # Use functions from library log_info "Script started" if check_command "git"; then log_info "Git is installed" else log_error "Git is not installed" fi

Practical Application Example

bash
#!/bin/bash # Function 1: Check if file exists check_file() { local file=$1 if [ -f "$file" ]; then return 0 else return 1 fi } # Function 2: Create backup create_backup() { local source=$1 local backup_dir=${2:-"./backup"} if ! check_file "$source"; then echo "Error: File $source does not exist" return 1 fi mkdir -p "$backup_dir" local timestamp=$(date +%Y%m%d_%H%M%S) local backup_file="$backup_dir/$(basename $source).$timestamp" cp "$source" "$backup_file" echo "Backup created: $backup_file" return 0 } # Function 3: Batch process files process_files() { local pattern=$1 local count=0 for file in $pattern; do if [ -f "$file" ]; then echo "Processing: $file" create_backup "$file" count=$((count + 1)) fi done echo "Processed $count files" return 0 } # Function 4: Show usage help show_help() { echo "Usage: $0 [options]" echo "Options:" echo " -f <file> Backup single file" echo " -p <pattern> Backup files matching pattern" echo " -h Show this help" } # Main program main() { case $1 in -f) if [ -n "$2" ]; then create_backup "$2" else echo "Error: No file specified" show_help fi ;; -p) if [ -n "$2" ]; then process_files "$2" else echo "Error: No pattern specified" show_help fi ;; -h) show_help ;; *) echo "Error: Invalid option" show_help ;; esac } # Execute main program main "$@"

Function Best Practices

  1. Use local for local variables: Avoid polluting the global namespace
  2. Use lowercase for function names: Follow Shell naming conventions
  3. Add comments: Explain function purpose and parameters
  4. Check parameters: Validate input parameters
  5. Return appropriate exit codes: 0 for success, non-zero for failure
  6. Use function libraries: Organize common functions into separate files
  7. Avoid side effects: Functions should focus on single responsibility
标签:Shell