Get the App
SLTechnology News&Howtos  ›  Development  › 

How shell uses functions

Shulou Source: shulou.com Published: 2022-06-01 04:01:20 09月28日 Update

This article is about how shell uses functions. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Function

Variables defined anywhere are global variables. If you want to define local variables, you need to add the local keyword

Functions in shell can also use recursion

#! / bin/bash function factorial {if [[$1-eq 1]]; then echo 1 else local temp=$ [$1-1] local result= `factorial $temp`echo $[$result * $1] fi} result= `factorial 5` echo $result

Create a function library

Set a function in another file, and then load it into the current file through the source command

Use functions in the exercise of commands

Define the function in ~ / .bashrc

Pass an array to a function

#! / bin/bash # adding values in an array function addarray {local sum=0 local newarray newarray= (`newarray "$@" `) for value in ${newarray [*]} do sum=$ [$sum+$value] done echo $sum} myarray= (12345) echo "The original array is: ${myarray [*]}" arg1= `echo ${myarray [*]} `result= `array $arg1`echo "The result is $result" Thank you for reading! This is the end of this article on "how to use functions in shell". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Function variable content command file more article good practical global key keyword local local array article see knowledge recursion reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Docker MariaDB Microsoft MySQL