What are Bash Functions in Linux?
Now that you have a basic idea of what are bash functions, let’s see how to define them to make our Linux workflow much easier. The basic syntax to define bash functions are:
You can even use the single-line version of the above syntax:
Some points to remember about defining bash functions include:
Let’s see a basic example based on the above syntax. Start by creating a new file inLinux text editorsand write this code inside it:
It is recommended to save the file with the same name as the function name. To invoke the file, simply write the function name inside the shell prompt and hit enter.
Sometimes you may need to work with some custom values or work with the user input values with the functions you’ve created. To pass arguments to the bash function, simply mention them after the function name after invoking the function as Linux shell variables. As for using the arguments inside the function, place them with$<argument_position>, like$1,$2below and so on. For example:
To invoke, use the following command:
Unlike other programming languages, in bash, you cannot return values from the function. You can only send the return status from the bash function to the caller with any number ranging from 0 to 255, where 0 represents success and any other number as a Linux system error/failure. For example, copy this code in thenano editor in Linux.
The scope of a variable means code parts where the variables can be used in bash. The scope can be divided into mainly two parts – global and local scope. With the global scope, the variable can be used everywhere including directly in the shell prompt. Local scope means the variable cannot be used outside the block where it is declared.
Bringing the latest in technology, gaming, and entertainment is our superhero team of staff writers. They have a keen eye for latest stories, happenings, and even memes for tech enthusiasts.