Linux function with parameters

Функции bash в скриптах

Наверное, всем известно, что у оболочки Bash есть встроенные команды, которых нет в папках /bin или /usr/bin. Они встроены в оболочку и выполняются в виде функций. В одной из предыдущих статей мы рассматривали написание скриптов на Bash. Мы обговорили там почти все, как должны выглядеть скрипты, использование условий, циклов, переменных, но не останавливались на функциях.

В сегодняшней статье мы исправим этот недостаток. Как и в любом языке программирования, в Bash есть функции их может быть очень полезно использовать. Мы рассмотрим использование функций bash, как их писать и даже как создавать библиотеки из этих функций.

Написание функций Bash

Сначала нужно понять что такое функция в нашем контексте. Функция — это набор команд, объединенных одним именем, которые выполняют определенную задачу. Функция вызывается по ее имени, может принимать параметры и возвращать результат работы. Одним словом, функции Bash работают так же, как и в других языках программирования.

Синтаксис создания функции очень прост:

Имя функции не должно совпадать ни с одной из существующих команд или функций, а все команды в теле функции пишутся с новой строки.

Простая функция

Давайте напишем небольшую функцию, которая будет выводить строку на экран:

#!/bin/bash
printstr() echo «hello world»
>
printstr

Вызов функции bash выполняется указанием ее имени, как для любой другой команды. Запустите наш скрипт на выполнение, не забывайте, что перед этим нужно дать ему права на выполнение:

Все работает, теперь усложним задачу, попробуем передать функции аргументы.

Аргументы функции

Аргументы функции нужно передавать при вызове, а читаются они точно так же, как и аргументы скрипта. Синтаксис вызова функции с параметрами bash такой:

имя_функции аргумент1 аргумент2 . аргументN

Как видите, все достаточно просто. Параметры разделяются пробелом. Теперь улучшим нашу функцию, чтобы она выводила заданную нами строку:

!/bin/bash
printstr() echo $1
>
printstr «Hello world»

Можно сделать, чтобы параметров было несколько:

!/bin/bash
printstr() echo $1
echo $2
echo $3
echo $5
>
printstr «arg1» «arg2» «arg3» «arg4» «arg5»

Есть и другой способ извлекать аргументы, как в Си, с помощью стека. Мы извлекаем первый аргумент, затем сдвигаем указатель стека аргументов на единицу и снова извлекаем первый аргумент. И так далее:

!/bin/bash
printstr() echo $1
shift
echo $1
shift
echo $1
shift
echo $1
>
printstr «arg1» «arg2» «arg3» «arg4»

Возврат результата функции

Вы можете не только использовать функции с параметрами bash, но и получить от нее результат работы. Для этого используется команда return. Она завершает функцию и возвращает числовое значение кода возврата. Он может быть от 0 до 255:

!/bin/bash
printstr() return 134;
>
printstr
echo $?

Если вам нужно применить возврат значения функции bash, а не статус код, используйте echo. Строка не сразу выводится в терминал, а возвращается в качестве результата функции и ее можно записать в переменную, а затем использовать:

Читайте также:  В linux не работает boost

!/bin/bash
printstr() echo «test»
>
VAR=$(printstr)
echo $VAR

Экспорт функций

Вы можете сделать функцию доступной вне скрипта с помощью команды declare:

!/bin/bash
printstr() echo «hello world»
>
declare -x -f printstr

Затем запустите скрипт с помощью команды source:

source function.sh
$ printstr

Рекурсия

Вы можете вызвать функцию из нее же самой, чтобы сделать рекурсию:

!/bin/bash
printstr() echo «hello world»
printstr
>
printstr

Вы можете поэкспериментировать с использованием рекурсии, во многих случаях это может быть полезным, только не забывайте делать первый вызов функции Bash.

Локальные переменные в функции

Если вы объявите обычную переменную в функции, то она будет доступной во всем скрипте, это удобно для возврата значения функции, но иногда может понадобиться сделать локальную переменную. Для этого существует команда local:

!/bin/bash
printstr() local VAR=$1
echo $
>
printstr «Hello World»

Библиотеки функций

Мы можем взять некоторые функции bash и объединить их в одну библиотеку, чтобы иметь возможность одной командой импортировать эти функции. Это делается похожим образом на экспорт функций. Сначала создадим файл библиотеки:

test1() echo «Hello World from 1»;
>
test2() echo «Hello World from 2»;
>
test3() echo «Hello World from 3»;
>

Теперь создадим скрипт, который будет использовать наши функции. Импортировать библиотеку можно с помощью команды source или просто указав имя скрипта:

!/bin/bash
source lib.sh
test1
test2
test3

Выводы

В этой статье мы рассмотрели функции bash, как их писать, применять и объединять в библиотеки. Если вы часто пишете скрипты на Bash, то эта информация будет для вас полезной. Вы можете создать свой набор функций, для использования их в каждом скрипте и тем самым облегчить себе работу.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Create Bash Functions with Arguments

To create efficient code, bash functions are used in shell scripts. In essence, these are a set of instructions that can be used again throughout the program. Additionally, it enables programmers to divide long, complex scripts into manageable chunks that may be invoked as needed. In this article, we will go through how to pass an argument to a bash function to build a function with an argument. The parameter may be a string, an integer, or something else entirely. Different methods of sending arguments to bash functions will be used in this article.

Passing Argument to the Bash Function

In this section, we will show you how to provide an argument for a bash function in Linux. But first, we will demonstrate how to create a function in bash. The use of functions in bash scripting is a fantastic way to reuse content. A group of commands that can be called repeatedly within a bash script might be referred to as a bash module. Functions in bash are there to make your programs easier to read and prevent you from entering the same script repeatedly.

For writing the program, we will use the bash shell, which is “#!/bin/bash.” Then, in the following line, we will define an essentially user-defined function, so we will give it the name of our choice. Here, we will name the function “func,” and we will use the round brackets “()” that we know are used with functions. We will then use curly brackets inside of these brackets. We use the “echo” command to print the statement that contains the text “I love my country” and because this statement is embedded in the function, it will be displayed in the output when the function is called. The function will now be called at the end of the script. Simply enter the method name “func” without any parentheses to accomplish this.

Читайте также:  Open key file linux

The command to display the output of a bash script in the terminal will now be entered into the terminal. To do this, we will first enter the keyword “bash” followed by a space, then the name of the bash script, “filebash.sh”.

The string that we used inside the function “func” and wanted to display on the screen after calling the function will be displayed when we run this command. As you can see, the sentence “I love my country” is displayed in the image below.

Now, in the following section, we will give an argument for the bash function. To do this, we’ll construct a script in bash in which we first add the shell, as we did earlier, then define a function with the name “func1(),” followed by curly brackets. The body of the function is located within the curly brackets. Therefore, inside the body of the function, we use the “echo” command to print the function name “func1” and pass the bash parameter “$1”. After exiting the function’s body, we call it in the following line and pass the string “Goodluck” as an argument. This string is kept in the variable “$1”.

The script’s output is then displayed on the terminal by typing the same command that is also utilized in the previous step.

As you can see in the image below, when we ran this command, it displayed a statement that included the function name “func1” as well as the string “Goodluck” that we had supplied as an argument to the bash function. It will be saved in the parameter “$1”.

Passing Multiple Arguments to the Bash Function

While this section is similar to the one before it, we will pass multiple parameters here rather than a single argument in the earlier section. For this, we are going to develop a script in which we first add the bash shell, which is “#!/bin/bash,”. Then, define a function with the name “user_function(),” followed by the body of the function, which is created using curly brackets. In between these brackets, we follow the identical steps as in the previous section, inputting the statement “user_function” which is the name of the function and the parameters “$1”, “$2”, “$3”, and “$4” with the “echo” command.

Then, in the following step, we will call the function with the arguments by using the name of the function, “user_function,” as well as the four strings that make up the argument: “I”, “love”, “my” and “country”. The strings must be written with inverted commas. The parameters for bash will be replaced with these strings that we supply as arguments. The first string will be stored in “$1,” the second in “$2,” the third in “$3,” and the fourth in “$4”.

Читайте также:  Терминал linux последовательный порт

#!/bin/bash
user_function ( ) {
echo “user_function $1 $2 $3 $4 ”
}
user_function “I” “love” “my” “country”

Now, we are going to use the command to open the bash script on the terminal by first typing “bash” and then the script’s name, “filebash.sh”.

You can see in the image below that when the command is successfully executed, it displays the function name, “user function,” as well as the string “I love my country” which we had supplied as an argument in the bash function.

Using the Division Method in the Bash Function with an Integer Argument

In this section, we will divide an integer using a bash script and send the result as input to the function. To accomplish this, we will write a script in which we first add the bash shell as we did in the previous step. Then, define the function “user function()” then use curly brackets inside of which we define the variable “div” and store the division operation using the dollar sign “$.” We then use double round brackets inside of which we use two parameters, “$1” and “$2,” and between these two parameters we insert the division operator to perform division.

Then, we use the “echo” command in the following line, passing the input statement “dividing 60 by 10 is” as well as the argument “div” with the value “$” because the answer of the division is stored in it. The values we use in the division, “60” and “10,” will be passed as arguments to the function when we call it using the function “user_define.”

#!/bin/bash
user_function ( ) {
div =$ ( ( $1 / $2 ) )
echo “dividing 60 by 10 is : $div ”
}
user_function 60 10

The following command should be used to display the outcome on the screen as the subsequent step.

You can see the division’s outcome shown when we run this command. The outcome is “6” as shown by the statement, which states “division 60 by 10 is: 6.”

Conclusion

This article has discussed how to write a bash function in Linux that takes arguments. In a bash function, various techniques for sending arguments have been defined. In the first section of this article, we covered how to write a script in bash and build a function, as well as how to provide a single argument to a function. The numerous parameters are supplied to a bash function in the second half, and the integer argument is passed in the last section to perform division.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Оцените статью
Adblock
detector