function::- - Linux


function::- is a bash built-in command that defines a user-created function. Functions allow you to group multiple commands into a reusable unit, simplifying complex scripts and enhancing code organization.


function function_name {
  # Function definition goes here




Example 1: Create a Function for Greeting Users

function greet {
  echo "Hello $1, welcome to the system!"

greet John

Example 2: Define a Function with Multiple Arguments and Default Values

function power {
  local base=$1
  local exponent=${2:-2}
  echo $(echo "$base^$exponent" | bc)

power 2 3  # Output: 8
power 5     # Output: 25 (uses default exponent value of 2)

Common Issues

  • Forgetting to Invoke the Function: Remember to call the function using its name after defining it. For example: function_name.
  • Duplicate Function Names: Avoid reusing existing function names, as this can lead to errors or unexpected behavior.
  • Missing Curly Braces: The function definition must be enclosed within curly braces {}.


Example: Utilizing function::- to Create a Script


function backup {
  tar -czvf backup_$(date +"%Y-%m-%d").tar.gz /important_directory

# Create a daily backup script using crontab
crontab -e
# Add the following line to the crontab file:
0 0 * * * backup

Related Commands

  • typeset: Declares and modifies shell variables.
  • eval: Evaluates a given string as a shell command.
  • bash: Bash command-line shell.