Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 73

Functions

Оглавление

Functions are a way to organize your Bash script into logical sections instead of having an unorganized structure (programmers call it spaghetti code). Let's take the earlier calculator program and reorganize it (refactor it) to make it look better.

This Bash script (in Figure 2.3) is divided into three sections:

 In the first section, we create all the global variables. Global variables are accessible inside any function you create. For example, we are able to use all the NUM variables declared in the example inside the add function.

 Next, we build the functions by dividing our applications into logical sections. The print_custom() function will just print any text that we give it. We're using the $1 to access the parameter value passed to this function (which is the string CALCULATOR ).

 Finally, we call each function sequentially (each one by its name). Print the header, add the numbers, and, finally, print the results.


Figure 2.3 Script Sections

Kali Linux Penetration Testing Bible

Подняться наверх