Unix / Linux - Shell Functions (2024)

Unix / Linux - Shell Functions (1)

  • Unix / Linux for Beginners
  • Unix / Linux - Home
  • Unix / Linux - Getting Started
  • Unix / Linux - File Management
  • Unix / Linux - Directories
  • Unix / Linux - File Permission
  • Unix / Linux - Environment
  • Unix / Linux - Basic Utilities
  • Unix / Linux - Processes
  • Unix / Linux - Communication
  • Unix / Linux - The vi Editor
  • Unix / Linux Shell Programming
  • Unix / Linux - Shell Scripting
  • Unix / Linux - What is Shell?
  • Unix / Linux - Using Variables
  • Unix / Linux - Special Variables
  • Unix / Linux - Using Arrays
  • Unix / Linux - Basic Operators
  • Unix / Linux - Decision Making
  • Unix / Linux - Shell Loops
  • Unix / Linux - Loop Control
  • Unix / Linux - Shell Substitutions
  • Unix / Linux - Quoting Mechanisms
  • Unix / Linux - IO Redirections
  • Unix / Linux - Shell Functions
  • Unix / Linux - Manpage Help
  • Advanced Unix / Linux
  • Unix / Linux - Regular Expressions
  • Unix / Linux - File System Basics
  • Unix / Linux - User Administration
  • Unix / Linux - System Performance
  • Unix / Linux - System Logging
  • Unix / Linux - Signals and Traps
  • Unix / Linux Useful Resources
  • Unix / Linux - Useful Commands
  • Unix / Linux - Quick Guide
  • Unix / Linux - Builtin Functions
  • Unix / Linux - System Calls
  • Unix / Linux - Commands List
  • Unix / Linux - Useful Resources
  • Unix / Linux - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

In this chapter, we will discuss in detail about the shell functions. Functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their individual tasks when needed.

Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an important part of modern object-oriented programming principles.

Shell functions are similar to subroutines, procedures, and functions in other programming languages.

Creating Functions

To declare a function, simply use the following syntax −

function_name () { list of commands}

The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.

Example

Following example shows the use of function −

#!/bin/sh# Define your function hereHello () { echo "Hello World"}# Invoke your functionHello

Upon execution, you will receive the following output −

$./test.shHello World

Pass Parameters to a Function

You can define a function that will accept parameters while calling the function. These parameters would be represented by $1, $2 and so on.

Following is an example where we pass two parameters Zara and Ali and then we capture and print these parameters in the function.

#!/bin/sh# Define your function hereHello () { echo "Hello World $1 $2"}# Invoke your functionHello Zara Ali

Upon execution, you will receive the following result −

$./test.shHello World Zara Ali

Returning Values from Functions

If you execute an exit command from inside a function, its effect is not only to terminate execution of the function but also of the shell program that called the function.

If you instead want to just terminate execution of the function, then there is way to come out of a defined function.

Based on the situation you can return any value from your function using the return command whose syntax is as follows −

return code

Here code can be anything you choose here, but obviously you should choose something that is meaningful or useful in the context of your script as a whole.

Example

Following function returns a value 10 −

#!/bin/sh# Define your function hereHello () { echo "Hello World $1 $2" return 10}# Invoke your functionHello Zara Ali# Capture value returnd by last commandret=$?echo "Return value is $ret"

Upon execution, you will receive the following result −

$./test.shHello World Zara AliReturn value is 10

Nested Functions

One of the more interesting features of functions is that they can call themselves and also other functions. A function that calls itself is known as a recursive function.

Following example demonstrates nesting of two functions −

#!/bin/sh# Calling one function from anothernumber_one () { echo "This is the first function speaking..." number_two}number_two () { echo "This is now the second function speaking..."}# Calling function one.number_one

Upon execution, you will receive the following result −

This is the first function speaking...This is now the second function speaking...

Function Call from Prompt

You can put definitions for commonly used functions inside your .profile. These definitions will be available whenever you log in and you can use them at the command prompt.

Alternatively, you can group the definitions in a file, say test.sh, and then execute the file in the current shell by typing −

$. test.sh

This has the effect of causing functions defined inside test.sh to be read and defined to the current shell as follows −

$ number_oneThis is the first function speaking...This is now the second function speaking...$

To remove the definition of a function from the shell, use the unset command with the .f option. This command is also used to remove the definition of a variable to the shell.

$ unset -f function_name

Advertisem*nts

';adpushup.triggerAd(ad_id); });

Unix / Linux - Shell Functions (2024)

FAQs

What are the functions of the shell in Unix? ›

After you type a command, it is the responsibility of the shell to (a) parse the command line; (b) handle wildcards, redirection, pipes, and job control; and (c) search for the command, and if found, execute that command. When you first learn UNIX/Linux, you spend most of your time executing commands from the prompt.

What are the basic functions of shell? ›

Shells provide a way for you to communicate with the operating system. This communication is carried out either interactively (input from the keyboard is acted upon immediately) or as a shell script. A shell script is a sequence of shell and operating system commands that is stored in a file.

What are the commands in the shell of Unix? ›

Unix shell commands are of three types basic, intermediate, and advanced, consisting of various commands like ls, cat, rm, mv, mkdir, chmod, find, chown, chgrp, head, tail, grep, ln, cut, etc.

What are the functions in Linux? ›

The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient.

What is a Bash function? ›

Bash functions allow you to create reusable blocks of code that can perform complex operations, organize your code, and simplify your scripts. You can pass arguments to a Bash function, which can then be used within the function to perform operations on those arguments.

What is the difference between Bash and shell in Unix? ›

In summary, while "shell" is a broad term that refers to any program that provides a command-line interface, "Bash" is a specific type of shell that is widely used in Unix/Linux systems.

What is the difference between kernel and shell? ›

The kernel is the lowest level of abstraction, dealing with the hardware directly and performing the essential functions of the operating system. The shell is a higher level of abstraction, providing a convenient and flexible way for users to interact with the operating system and its features.

What are the functions of each of the shell structures? ›

Shell structures are self-supporting and used to cover a large area of span without any supports of beams, columns, and walls. Its efficiency is based on its curvature (single or double), which allows different stress paths and gives the optimum form for transmission of many different load types.

What is the difference between Linux and Unix? ›

Linux is an open-source operating system. This OS is supported on several computer platforms and includes multiple software features that handle computer resources, and allow you to do tasks. Unix is a powerful and multitasking operating system that behaves like a bridge between the user and the computer.

Are Linux and Unix commands same? ›

Common commands such as ls, cd, mkdir, rm, and grep work identically across Linux and Unix environments. Depending on the specific distribution, there may be slight variations in command options, syntax, and the availability of certain tools.

How to use shell command in Linux? ›

Some of the essential basic shell commands in Linux include:
  1. cd (Change Directory): Allows navigation between directories. ...
  2. ls (List): Lists the contents of a directory. ...
  3. mkdir (Make Directory): Creates a new directory. ...
  4. cp (Copy): Copies files or directories from one location to another.
Nov 30, 2023

How do I list all functions in Linux? ›

The usual way is to use declare -f which will print a very long list of functions in an interactive bash shell. But inside an script, as most external functions are not defined, the list will be short and useful.

Is there a main function in shell script? ›

typically use a main() program function that calls exit(0) (or other integer value) to exit the program and pass the integer value to the shell as the program exit status. Shell scripts can call exit 0 (or other integer value) to indicate the exit status of the script.

How do I remember commands in Linux? ›

  1. Use filename and command completion. Both filename and command completion can help you to specify files and enter commands. ...
  2. Use an intuitive shell. Another option for helping recall Linux commands is to use a shell like fish that offers features such as suggesting command completion. ...
  3. Use a cheat sheet. ...
  4. Use man pages.

What is the function of kernel and shell in Unix? ›

A kernel is the very core of a typical OS. A shell is a CLI (command-line interpreter). A kernel is a type of low-level program that has its interfacing with the hardware on top of which all the applications run (disks, RAM, CPU, etc.). A shell allows all of its users to establish communication with the kernel.

What is defining functions in shell? ›

Definition of shell script functions

Functions are defined with a name, a set of parameters (optional), and a block of code that performs some operation. The code inside the function can access and modify variables within the function or outside the function, depending on their scope.

What is the shell in Unix file system? ›

UNIX shells provide a "command line" interface which allows the user to enter commands which are translated by the shell into something the kernel can comprehend and then is sent off to the kernel for it to act upon. The user can pick their shell (just like the applications, desktop manger, window manager, etc.

Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6028

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.