Ad space (banner)
Lesson 8 / 20

Writing your own function

This lesson covers the basic form for defining a function in a shell script.

A function is defined as name() { ... }. Arguments arrive as $1, $2, and so on — the same notation as the script's own arguments.

The sample code defines greet() { echo "Hello, $1!"; } and calls it as greet "Bob".

A common early stumble is how to return a value from a function. The return value of most languages can only carry a numeric exit status (0–255) here, so when you want a string result the usual approach is to echo it and capture it at the call site with $( ).

In professional work, gathering logic into a function in one place, rather than copying it around, is what keeps a script maintainable.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Shell Script directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)