function - Linux


In Linux, function is not a standalone command but a shell keyword used primarily in Bash and other shell environments to define function routines. A function in a shell script or command line is a name assigned to a block of code for the purpose of reusing that code multiple times throughout the script. This enhances the script’s efficiency, reduces redundancy, and improves readability.


The syntax to define a function in Bash is as follows:

function name {


name() {

Here, name is the identifier for the function, and commands represent one or more commands to be executed within the function.


  • name: The name of the function. It should be unique within the scope of the script or terminal session.
  • commands: A list of commands that are executed when the function is called.


Since function is a keyword and not a command, it does not have options or flags. The behavior of the function is defined by the commands inside the function block.


Example 1: Basic Function

function greet {
    echo "Hello, $1!"

Call the function:

greet World


Hello, World!

Example 2: Function with Local Variable

function sum {
    local a=$1
    local b=$2
    echo $((a + b))

Call the function:

sum 5 3



Common Issues

  • Naming Conflicts: Function names conflicting with existing command names can lead to unexpected behavior. Always choose unique names or check the function name using type function_name.
  • Scope: By default, variables created in functions are global. Use the local keyword to limit their scope to within the function.


Functions can be integrated with other shell scripts and commands to form more complex operations.

Example: Function in a Script


function check_ping {
    ping -c 1 $1 > /dev/null
    if [ $? -eq 0 ]; then
        echo "$1 is reachable."
        echo "$1 is not reachable."

# Check a list of hosts
hosts=("" "" "")
for host in "${hosts[@]}"; do
    check_ping $host
  • alias: Create aliases for commands, similar to functions but typically used for simpler command substitutions.
  • export: Used to define environment variables that can be inherited by sub-processes, not directly related but often used together with functions.

For deeper insights into writing effective shell functions, consider referring to the Advanced Bash-Scripting Guide.