Course outline · 0% complete

0/29 lessons0%

Course overview →

Functions and real automation

lesson 9-3 · ~11 min · 26/29

Functions: name a block of commands

A function is a reusable mini-script inside your script:

greet() {
  echo "Hello, $1!"
}
greet Ada

Define once with name() { ... }, call by name like any command. Inside the function, $1, $2, $# refer to the function's arguments, exactly like a script's arguments in lesson 8-2. This is how a growing script stays readable: small named pieces.

Code exercise · bash

Run it: one function, two calls, different argument each time.

Automation #1: batch rename

Everything converges. Renaming 300 files by hand is an afternoon, or it's three lines:

for f in *.txt; do
  mv "$f" "${f%.txt}.md"
done

One new tool: ${f%.txt} is the variable's value with .txt chopped off the end (the % means "remove this suffix"). So notes.txt → notes → notes.md. The quotes around "$f" keep filenames with spaces in one piece, a habit worth building now.

Code exercise · bash

Run the batch renamer: three .txt files become .md in one loop (lesson 3-2's mv doing the renaming).

Automation #2: a log summarizer

A function + grep -c (lesson 4-1) = an instant report tool for any log file. Notice $(command) below: command substitution captures a command's output into the middle of a string, the same trick you used with $(pwd) in lesson 2-1.

Code exercise · bash

Your turn. The starter builds a 5-line app.log and defines the report shape. Complete the summarize function so it prints the error and warning counts of the file named in $1. Expected output: ``` errors: 2 warnings: 1 ```

Quiz

Inside a function called as `deploy staging fast`, what is $2?