Bash Tutorial
Estimated reading: 4 minutes 40 views

πŸ”§ Bash Functions & Scripting – Build Modular, Maintainable Shell Scripts

🧲 Introduction – Master the Art of Bash Automation

Bash scripting isn’t just about running commandsβ€”it’s about structuring logic, modularizing tasks, handling inputs, and responding to events. This guide walks you through defining functions, passing parameters, handling script arguments, performing redirection, and even using traps for signal cleanup.

🎯 In this guide, you’ll learn:

  • How to define and call functions with parameters
  • How to write well-structured scripts using shebang and arguments
  • How to redirect output and debug scripts
  • How to build interactive select menus
  • How to trap signals and control exit behavior

πŸ“˜ Topics Covered

πŸ”Ή TopicπŸ“– Description
🟒 Bash: Defining FunctionsUse function or () to declare modular code blocks
🟒 Bash: Function Parameters & Return ValuesPass arguments and use return for exit codes
🟒 Bash: Script Header & Structure (#!/bin/bash)Add a shebang and organize script logic
🟒 Bash: Script Arguments ($1, $2, etc.)Handle positional parameters and argument validation
🟒 Bash: Running Scripts (bash script.sh, ./script.sh)Execute Bash files and make them executable
🟒 Bash: IO Redirection in ScriptsRedirect output (>, >>, 2>) and input (<)
🟒 Bash: Select Menus (select)Create user-friendly menu-based interfaces
🟒 Bash: Debugging (set -x, -n, -v)Enable step-by-step tracing, syntax check, and verbose output
🟒 Bash: Trap, Signals & Exit Codes (trap, exit)Clean up resources and handle signals or abnormal terminations

🟒 Bash: Defining Functions (function, (), return)

πŸ”Ή Syntax:

greet() {
  echo "Hello, $1"
}
greet "World"

Or:

function greet {
  echo "Hello, $1"
}

βœ… Use return <code> to set an exit code (0 = success).


🟒 Bash: Function Parameters & Return Values

add() {
  result=$(( $1 + $2 ))
  echo "Sum: $result"
  return 0
}

add 3 5
echo "Function exited with code $?"

βœ… Use $1, $2, etc., inside functions like scripts.


🟒 Bash: Script Header & Structure (#!/bin/bash)

Every Bash script should start with:

#!/bin/bash

πŸ”Ή Example Layout:

#!/bin/bash

# Define function
say_hello() {
  echo "Hello, $1"
}

# Call function
say_hello "User"

βœ… Save as script.sh, then run using bash script.sh or chmod +x script.sh.


🟒 Bash: Script Arguments ($1, $2, $@, $#)

echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Total args: $#"

βœ… Always validate arguments before use:

if [[ $# -lt 1 ]]; then
  echo "Usage: $0 filename"
  exit 1
fi

🟒 Bash: Running Scripts (bash script.sh, ./script.sh)

  • Execute directly:
chmod +x script.sh
./script.sh arg1 arg2
  • Or use Bash interpreter:
bash script.sh arg1

βœ… Use the shebang line (#!/bin/bash) to allow direct execution.


🟒 Bash: IO Redirection in Scripts (>, <, >>, 2>)

SymbolPurpose
>Redirect stdout (overwrite)
>>Append stdout
2>Redirect stderr
<Redirect input from file
&>Redirect both stdout and stderr

πŸ”Ή Example:

echo "Hello" > out.txt
cat < out.txt
ls /fakepath 2> error.log

🟒 Bash: Select Menus (select)

select opt in "Start" "Stop" "Exit"; do
  case $opt in
    "Start") echo "Starting...";;
    "Stop") echo "Stopping...";;
    "Exit") break;;
    *) echo "Invalid";;
  esac
done

βœ… select is ideal for interactive command-line menus.


🟒 Bash: Debugging (set -x, set -n, set -v)

OptionDescription
-xPrint commands before executing
-nSyntax check only (dry run)
-vEcho input lines as they’re read

πŸ”Ή Example:

set -x
echo "Debugging this line"
set +x

βœ… Great for troubleshooting long scripts.


🟒 Bash: Trap, Signals & Exit Codes (trap, exit)

πŸ”Ή Use trap to clean up:

cleanup() {
  echo "Cleaning up..."
}
trap cleanup EXIT

πŸ”Ή Trap SIGINT:

trap "echo Interrupted!" SIGINT

βœ… Use exit 0 for success, exit 1 or higher for error conditions.


πŸ“Œ Summary – Bash Functions & Scripting

Bash scripting allows you to write modular, maintainable, and reusable code using functions, parameters, and redirection. With traps, menus, and debugging tools, your scripts become production-grade automation tools.

πŸ” Key Takeaways:

  • Define functions using () or function for reusability
  • Use $1, $2, $@ for arguments in scripts and functions
  • Add shebang (#!/bin/bash) to make scripts executable
  • Redirect input/output and handle errors with redirection operators
  • Use select for user choices, and trap for signal handling
  • Enable debugging using set -x or syntax check with set -n

βš™οΈ Real-World Applications:

  • Scheduled cron job scripts
  • Backup and log rotation automation
  • User-driven shell tools and server maintenance scripts

❓ Frequently Asked Questions: Bash Functions & Scripting

❓ Can a Bash function return a string?
βœ… Not directly. Use echo inside the function and capture with var=$(func).


❓ How do I make a Bash script executable?
βœ… Use:

chmod +x script.sh

❓ What is the use of trap in Bash?
βœ… It allows you to run cleanup code on signals like SIGINT, EXIT, etc.


❓ How do I debug a Bash script?
βœ… Add set -x at the top or run as:

bash -x script.sh

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ”§ 4. Bash Functions & Scripting

Or Copy Link

CONTENTS
Scroll to Top