Linux: Simple Shell Functions

You can group a number of shell commands that you use consistently in Linux into a function and assign it a name. Later, you can execute that group of commands by using the single name assigned to the function. Here is a simple script that illustrates the syntax of shell functions:

#!/bin/sh
hello() {
echo -n "Hello, "
echo $1 $2
}
hello Jane Doe

When you run this script, it displays the following output:

Hello, Jane Doe

This script defines a shell function named hello. The function expects two arguments. In the body of the function, these arguments are referenced by $1 and $2. The function definition begins with hello() — the name of the function, followed by parentheses. The body of the function is enclosed in curly braces — { … }. In this case, the body uses the echo command to display a line of text.

The last line of the example shows how a shell function is called with arguments. In this case, the hello function is called with two arguments: Jane and Doe. The hello function takes these two arguments and prints a line that says Hello, Jane Doe.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com