How to Add Help Function in Bash Script [3 Methods]

Bash scripting offers a powerful means to automate tasks and streamline workflows in the command-line environment. However, as scripts grow in complexity, clarity and usability become paramount. One fundamental way of achieving this is the integration of a help method within Bash scripts. This article will dive into how to add the bash help method in the bash script.

What is the “help” Method Within a Function in Bash?

In bash scripting, the “help” method within a function is a convention used to provide usage instructions, instructions, command syntax, and other helpful information about the function or script to the user. It is not a built-in method or command in bash but rather a user-defined function named “help” typically included within scripts or functions to display usage information.

The “help” method is often called when the user requests help by passing a specific command-line option, such as -h or --help. When the help option is detected, the script or function invokes the “help” method to print out a concise and informative message explaining how to use the script or function, including details about available options, arguments, and usage examples.

Here is the basic syntax of how to add help method in a bash script:

show_help() {
  echo "Usage: $(basename $0) [OPTIONS]"
  echo "Options:"
  echo "  -h, --help     Display this help message"
  echo "  -v, --version  Display version information"
  # Add more options and descriptions as needed
  exit 0
}

if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  show_help
fi

Here the show_help function is defined to display usage instructions and available options when the script is executed with the -h or --help option.

3 Methods to Add Bash “help” Function

The “help” method provides users with crucial guidance on script usage, options, and functionalities. This article will explore various approaches, from leveraging built-in commands like “getopts” to crafting custom conditional statements.

1. Using the “getopts” Command

The “getopts” is a built-in shell command in bash that facilitates the parsing of command line options and arguments. It simplifies the process of handling the command line arguments by providing a convenient way to iterate over options and their arguments. This command streamlines the creation of the help method in the  Bash script by efficiently managing command-line inputs and their corresponding actions.

The following bash script which creates a rectangular pattern uses the “getopts” command to create a help method for the bash script:

#!/bin/bash

# Default values
length=3
width=2

# Define the help method
help() {
  echo "Usage: $(basename $0) [-h] [-l LENGTH] [-w WIDTH]"
  echo "Options:"
  echo "  -h, --help     Display this help message"
  echo "  -l, --length   Set the length of the rectangular pattern"
  echo "  -w, --width    Set the width of the rectangular pattern"
  exit 0
}

# Parse command-line options
while getopts ":hl:w:" opt; do
  case $opt in
    h) help ;;
    l) length=$OPTARG ;;
    w) width=$OPTARG ;;
    \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
  esac
done

# Main script logic
for (( i = 0; i < length; i++ )); do
  for (( j = 0; j < width; j++ )); do
    echo -n "* "
  done
  echo
done
EXPLANATION

This Bash script generates a rectangular pattern of asterisks, with default dimensions of 3 rows by 2 columns. It allows users to customize the dimensions using command line options. The script defines a help method to display usage instructions and available options. It then parses command line options using the “getopts” command to allow users to specify the pattern’s length and width. Then the script iterates through the specified dimensions and prints the rectangular pattern using nested loops.

In bash scripting add the help method within a function using "getopts" command

Here, the script is executed with the help option to check the usage case and the available options.

2. Using the “if” Statement

In bash scripting, the if statement is used to execute a block of code on the evaluation of a condition. It helps in controlling the flow of the script. It can be used within the bash script to check whether the user has provided the -h or --help option. If the script detects the help option then it can echo the usage instructions and available options to the user. Which helps the user to understand how to use the script and its functionalities effectively. In the following script the if conditional statement creates and handles the help method:

#!/bin/bash

# Define the help method
if [[ $1 == "-h" || $1 == "--help" ]]; then
  echo "Usage: $(basename $0) [NUM]"
  echo "Options:"
  echo "  NUM            Number of elements in the Fibonacci sequence"
  echo "  -h, --help     Display this help message"
  exit 0
fi

# Fibonacci sequence logic
if [ -z "$1" ]; then
  echo "Error: Missing argument. Please provide the number of elements in the Fibonacci sequence."
  exit 1
fi

n=$1
a=0
b=1
echo "Fibonacci Sequence:"
for (( i=0; i<n; i++ )); do
  echo -n "$a "
  temp=$((a + b))
  a=$b
  b=$temp
done
echo
EXPLANATION

This bash script generates a fibonacci sequence based on the user-provided number of elements. It begins by checking if the user requested for help method. If so then it displays the usage instructions and available options. Then it verifies if the user has provided the number of elements for the fibonacci sequence. If not then it prompts the user to provide the missing number. If it gets a valid number then the script calculates and echoes the fibonacci sequence using a for loop.

In bash scripting add the help method within a function using "if" statement

Here, after the script is executed with the help option the script’s use cases and the options are shown.

3. Using the Conditional Statement

The conditional statement is a programming construct that allows to execution of different blocks of code based on the evaluation of a condition. In other words, it enables the user to control the flow of the script by making decisions. In bash scripting, conditional statements are often used to check for certain conditions and perform action accordingly.

To create a help method for a bash function, you can use conditional statements to check if the user has requested help by passing a specific flag or option like -h or --help. If a help option is detected then the script can display usage instructions, command syntax, and a list of available options to guide the user on how to use the script or function effectively.

Here is a bash script to showcase how to do so:

#!/bin/bash

# Define the help method
get_help() {
  echo "Usage: $(basename $0) [-h] [-s NUM] [-r NUM] [NUM1] [NUM2] [OPERATOR]"
  echo "Options:"
  echo "  -h, --help      Display this help message"
  echo "  -s, --square    Calculate the square of a number"
  echo "  -r, --root      Calculate the square root of a number"
  echo "  NUM1            First number for arithmetic operation"
  echo "  NUM2            Second number for arithmetic operation"
  echo "  OPERATOR        Arithmetic operator (+, -, *, /)"
  exit 0
}

# Check if no arguments provided
if [ $# -eq 0 ]; then
  echo "Error: No arguments provided."
  get_help
fi

# Parse command-line options
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
  get_help
elif [ "$1" == "-s" ] || [ "$1" == "--square" ]; then
  if [ -z "$2" ]; then
    echo "Error: Missing argument for square operation."
    exit 1
  else
    echo "Square of $2: $(echo "$2^2" | bc)"
    exit 0
  fi
elif [ "$1" == "-r" ] || [ "$1" == "--root" ]; then
  if [ -z "$2" ]; then
    echo "Error: Missing argument for root operation."
    exit 1
  else
    echo "Square root of $2: $(echo "sqrt($2)" | bc)"
    exit 0
  fi
fi

# Check for correct number of arguments for arithmetic operations
if [ "$#" -ne 3 ]; then
  echo "Usage: $(basename $0) NUM1 NUM2 OPERATOR"
  exit 1
fi

# Perform arithmetic operations
num1=$1
num2=$2
operator=$3

case $operator in
  +) echo "Sum of $num1 and $num2: $(echo "$num1 + $num2" | bc)" ;;
  -) echo "Difference of $num1 and $num2: $(echo "$num1 - $num2" | bc)" ;;
  \*) echo "Product of $num1 and $num2: $(echo "$num1 * $num2" | bc)" ;;
  /) 
    if [ "$num2" -eq 0 ]; then
      echo "Error: Cannot divide by zero."
      exit 1
    else
      echo "Quotient of $num1 and $num2: $(echo "scale=2; $num1 / $num2" | bc)"
    fi ;;
  *) echo "Invalid operator: $operator. Supported operators are +, -, *, /" ;;
esac
EXPLANATION

This bash script serves as a basic arithmetic calculator with support for various operations. It starts by defining a help method that displays usage instructions and available options when prompted by the user. The script then checks if any arguments are provided. If not displays an error message along with the help message. It also parses the command line options to calculate the square or square root of a number with -s and -r options respectively. It also can perform basic arithmetic operations based on the provided numbers and the operator and echoes the output accordingly.

In bash scripting add the help method within a function using conditional statement

Here, first, the bash script is executed with the help option to check the usages and options of the bash script. Then the script was called multiple times to showcase the use cases of those options.

Practice Tasks on the Bash “help” Function

If you aim to be better at using the Bash help method, then you can try creating a Bash script for the following problems with the Bash help method:

  1. Create a Bash script with the help method that calculates the factorial of a given number.
  2. Write a Bash script that checks whether a given number is prime or not. Include the help method.

Conclusion

In conclusion, including a “help” method within a Bash script or function is a best practice for ensuring that users can easily understand how to interact with the script or function and leverage its features effectively. I hope this article will help you manage and document your bash function and script more efficiently and let you have a better Linux experience.

People Also Ask

What is the help command in bash?

The help command in bash is a built-in command that provides information and documentation about other bash shell built-in commands and functions. It allows users to access concise descriptions, usage examples, and syntax details for various commands directly from the command line interface. Users can simply type help followed by the command name they want to learn more about to retrieve information. This command is invaluable for beginners learning bash and experienced users seeking quick reference materials fostering efficient command line navigation and troubleshooting.

What does $@ mean in bash?

In Bash scripting, $@ represents all the command-line arguments passed to a script or function. It preserves the exact words and spacing of each argument as they were provided. Unlike $*, which treats all arguments as a single entity, $@ allows for the individual handling of each argument. This distinction is crucial for scripts that need to process multiple arguments separately. By using $@, scripts can iterate through and manipulate each argument independently.

What does $0 mean in bash?

In bash scripting, $0 represents the name of the script or shell program being executed. It allows scripts to refer to themselves dynamically enabling self-referential behavior. When a script is invoked $0 provides the script’s filename or the name of the shell command being executed. This variable is useful for scripts that need to determine their own names for logging, error handling, or self-awareness purposes.

How do I call help in Linux?

To call for help in Linux, you can use the man command followed by the name of the command, utility or topic you need assistance with. For example, to learn about the ls command, you can type man ls in the terminal and press ENTER. This action opens the manual page for the specified command, displaying detailed information, options, and usage instructions. The man command is a powerful tool for accessing comprehensive documentation directly from the terminal.

What is command line help?

Command line help refers to the assistance and guidance provided to users directly from the command line interface of an operating system or software application. It typically includes documentation, usage instructions, and descriptions of available commands, options, and functionalities. Command line help enables users to quickly access information about specific commands or utilities, aiding them in understanding how to use the software effectively. By typing commands such as help or appending --help to a command, users can retrieve contextual help directly within the command line interface.

What is $# in bash?

In Bash scripting, $# represents the number of positional parameters passed to a script or function. It provides a count of arguments provided to the script or function when it is invoked. For example, if a script is called with three arguments, $# will return the value 3. This parameter is valuable for scripts that need to dynamically adapt their behavior based on the number of arguments provided during execution. By accessing $# within a Bash script, users can create more flexible and responsive scripts that handle varying numbers of inputs efficiently.

Related Articles


<< Go Back to Bash Function Examples | Bash Functions | Bash Scripting Tutorial

5/5 - (6 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Ridoy Chandra Shil

Hello everyone. I am Ridoy Chandra Shil, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Biomedical Engineering graduate from Bangladesh University of Engineering and Technology. I am a science and tech enthusiast. In my free time, I read articles about new tech and watch documentaries on science-related topics. I am also a big fan of “The Big Bang Theory”. Read Full Bio

Leave a Comment