ShellScript – Serial (P6)

Tram Ho

Let’s continue to explore the next part of the shell script!
? Function

1. Basic

  • Creating a function is quite simple. We can write in two different formats:

▪️ Note:

  • Both work the same way, and neither is faster than either.
  • In other programming languages, there are usually arguments passed to the function listed in parentheses () . In Bash, we will write without passing anything in parentheses.
  • The function definition must appear in the script before any commands can be called.
  • For example:

  • Line 3: We start defining the function by naming it.
  • Line 4: In curly brackets, we can write as many commands we want.
  • Lines 6, 7: Once the function has been defined, we can call it as many times as we want and it will execute those commands.

2. Pass parameters (Passing Argument)

  • We usually pass parameters when we want to process some data from outside, we will pass parameters right after the function name. Eg:

  • Results returned:


3. Return value

  • As we know, most programming languages ​​can return values ​​to functions, which serves as a means for functions to send data back to where they were called. But shell functions do not allow us to do that. However, it allows us to return the return status. It’s like making a program or a stop command a success. Here, we use return to indicate the return status. For example:

  • Line 5: Here, is the return status of a function.
  • Line 10: Variable $? Contains the return status of a previously run command or function.
  • Note: Usually, a return status of 0 indicates that everything was successful. A value other than 0 indicates an error has occurred.
  • Result:


In addition, we will add a bit about variable scope and command override

? Variable Scope
  • By default, the scope of a variable is global . That means it can be used anywhere in the script.
  • If we create a local variable in a function, it will only work in that function. The syntax will be as follows:

  • For example:

  • Result:

? Overriding Command
  • It is possible to name a function with the same name as a command we often use. For example:

  • Results returned:


Thank you for reading my article!
Share the news now

Source : Viblo