🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Functions

A function gives a block of commands a name you can run. You define it once, and call it whenever you need those commands.

Define and call a function

The name runs the whole block.

say_hello() {
  echo "Hello from a function"
}
say_hello

Pass an argument to a function

$1 inside the function is the caller's first word.

greet() {
  echo "Hello, $1"
}
greet Ana
greet Bo

A function that lists files

A function can hold any command.

list_txt() {
  echo *.txt
}
list_txt

A function with two commands

The block can hold more than one command.

show_date() {
  echo "Today is:"
  date -d '2026-01-15' '+%A %d %B %Y'
}
show_date

Example

cat > welcome.sh <<'EOF'
#!/bin/bash
greet() {
  echo "Hello, $1"
  echo "Welcome to Shell Beginner"
}
greet Ana
greet Bo
EOF
chmod +x welcome.sh
./welcome.sh

Key points

  • Function: name() { ... } gives a block of commands a name.
  • Call a function: type its name, as if it were a command.
  • Function arguments: $1 inside a function is the function's own first argument.
  • Use a function to give a repeated job one name.

In this example, the script defines a greet function. Then it calls it with Ana and then with Bo. Each call prints a greeting with that name.

Note

Define a function before you call it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does greet Ana print after you define greet to echo "Hello, $1"?