Shell Script

12 Making Function

트리스탄1234 2022. 8. 16. 13:35
728x90
반응형

 

1. Basic Script Finction

When writing a script, it is often necessary to write the same code in multiple scripts separately. For this, if the codes of commonly used scripts are made into functions, scripts that are written later do not need the entire code, but simply call the function.

Create a function

There are two forms of creating a function. Please see below..

The first form: how to define using the keyword function

function name {

commands

}

Second form:

A form that defines a function through empty parentheses.

name() {

commands

}

 

반응형

using functions

Let's look at an example using a function.

#!/bin/bash
# using a function in a script
function func1 { ==> Define a function.
echo "This is an example of a function"
}
count=1
while [ $count -le 5 ]
do
func1 ==> Call the function wherever you need it.
count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func1
echo "Now this is the end of the script"

if run tthis
$ ./test1
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
This is an example of a function
Now this is the end of the script
$

 

2. Return a value

The bash shell treats the function like a mini-script and completes with an exit code. There are three ways to create this exit code as follows.

Using the default exit code

The exit code value of a function depends on the execution result of the last line in the function. Returns 0 if the last command execution was successful, otherwise returns 1. If the default exit code is used, the results of execution of commands other than the execution result of the last line are unknown. Let's take a look at the example below.

#!/bin/bash
# testing the exit status of a function
func1() { ==> define function
ls -l badfile ==> command to fail
echo "This was a test of a bad command" ==> command to succeed
}
echo "testing the function:"
func1
echo "The exit status is: $?" ==> $?를 이용해서 exit code 알아보기
$ ./test4b
testing the function:
ls: badfile: No such file or directory
This was a test of a bad command
The exit status is: 0 ==>The exit code is 0 because the last line of the command is a success.
$

 

Using the return command

The bash shell can use the return command to exit a function with a specific exit code. Let's look at the example below.

#!/bin/bash
# using the return command in a function
function dbl {
read -p "Enter a value: " value
echo "doubling the value"
return $[ $value * 2 ] ==>Multiply the input variable and return the result
}
dbl
echo "The new value is $?" ==> reterive exit code
$
if run this
$ ./test5
Enter a value: 200
doubling the value
The new value is 1
$

 

The return command should look up as soon as the function exits. Doing a lookup before it's done will give you the values ​​you don't want. And secondly, the range of the returned value is from 0 to 255. In the above case, 1 was returned because the return value exceeded this range

Using the function output result

Just as the execution result of a command can be saved in a shell variable, the output result of a function can also be saved in a variable. You can use this to store the result of any type of function in a variable.

#!/bin/bash
# using the echo to return a value
function dbl {
read -p "Enter a value: " value
echo $[ $value * 2 ]
}
result=`dbl` ==>Save the execution result of db1 in result
echo "The new value is $result"
$ ./test5b
Enter a value: 200
The new value is 400

it run this
$ ./test5b
Enter a value: 1000
The new value is 2000
$

 

4. Using Variables in Functions

As input to functions, standard environment variables can be used as input on the command line. There are $0, $1, $2, etc. You can also use $#. How to use is as follows.

func $value1 10

Let's look at an example.

#! /bin/bash
# test passing value to function
function addem {
if [ $# -eq 0 ] || [ $# -gt 2 ] ===> If the number of input data is 0 or greater than 2
then
echo -1 ==>display -1
elif [ $# -eq 1 ] ==>If there is only one input
then
echo $[ $1 + $1 ] ==> Add one input value once
else
echo $[ $1 + $2 ] ==>If there are two inputs, add the two values.
fi
}
echo -n "Adding 10 and 15:"
value=`addem 10 15` ===>pass 2 inputs
echo $value
echo -n "Now trying adding no number:"
value=`addem` ==> No input
echo $value
echo -n "Finally, try adding three numbers:"
value=`addem 10 15 20` ==>input three inputted values
echo $value

if run this
$ ./test4
Adding 10 and 15:25
Now trying adding no number:-1
Finally, try adding three numbers:-1
$

Functions can use special environment variables as parameter values ​​of the function, but cannot directly access the value of the parameter from the command line. Let's look at the example below.

#!/bin/bash
# trying to access script parameters inside a function
function badfunc1 {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ]
then
value=`badfunc1`
echo "The result is $value"
else
echo "Usage: badtest1 a b"
fi

실행을 시켜 보면.
$ ./badtest1 ==> $1 $2,
The following error message occurs because parameters are not passed.
Usage: badtest1 a b
$ ./badtest1 10 15
==>The two parameters entered on the command line are not passed to the function.
./badtest1: * : syntax error: operand expected (error token is "*
")
The result is
$

 

Even if the $1 and $2 variables are used in the function, they are different from the $1 and $2 variables used in the script. When you want to use these values ​​in a function, you have to manually pass these parameters to the function. Let's take a look at the example below.

#!/bin/bash
# trying to access script parameters inside a function
function func7 {
echo $[ $1 * $2 ]
}
if [ $# -eq 2 ]
then
value=`func7 $1 $2`
echo "The result is $value"
else
echo "Usage: badtest1 a b"
fi

if run this
$ ./test7
Usage: badtest1 a b
$ ./test7 10 15
The result is 150
$

 

Handling Variables in Functions

One of the things that causes problems for script programmers is the scope of variables. Variables defined in a function have a different scope than regular variables. Variables in functions use the following two types of variables.

■ Global

■ Local

Global variable

A global variable is any variable defined in a script. Variables defined in such a script can be used within a function. Let's take a look at the example below

#!/bin/bash
# using a global variable to pass a value
function dbl {
value=$[ $value * 2 ]
}
read -p "Enter a value: " value
dbl
echo "The new value is: $value"

실행을 시켜 보면
$ ./test8
Enter a value: 450
The new value is: 900
$

 

Local variable

A variable can only be used inside a function. These are called local variables. If you declare local in front of a variable, it is used only in the function, and when you exit the function, the value is not used. Let's take a look at the example below.

#!/bin/bash
# demonstrating the local keyword
function func1 {
local temp=$[ $value + 5 ]
result=$[ $temp * 2 ]
}
temp=4 ==> 전역 변수 선언
value=6
func1 ==> 함수 호출
echo "The result is $result"
if [ $temp -gt $value ]
then
echo "temp is larger"
else
echo "temp is smaller"
fi

실행을 시켜 보면
$ ./test9
The result is 22
temp is smaller .
$

 

5. Array Variables and Functions

Passing an Array to a Function

When you pass an array to a function, it takes only the first value of the array and does not take the rest. In order to pass all the values ​​of the array to the function, there is a way to separate the values ​​of the array into individual variables and combine them into one array variable. Let's look at an example below

#!/bin/bash
# trying to pass an array variable
function testit {
echo "The parameters are: $@"
thisarray=$1
echo "The received array is ${thisarray[*]}"
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
testit $myarray

if run this
$ ./badtest3
The original array is: 1 2 3 4 5
The parameters are: 1
./badtest3: thisarray[*]: bad array subscript
The received array is
$

Then, modify the code and run it as shown below.
#!/bin/bash
# array variable to function test
function testit {
local newarray
newarray=(`echo "$@"`)
echo "The new array value is: ${newarray[*]}"
}
myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
testit ${myarray[*]}
$ ./test10
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5
$


Let's look at another example using the for statement.


#!/bin/bash
# adding values in an array
function addarray {
local sum=0
local newarray
newarray=(`echo "$@"`)
for value in ${newarray[*]}
do
sum=$[ $sum + $value ]
done
echo $sum
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=`echo ${myarray[*]}`
result=`addarray $arg1`
echo "The result is $result"

if runt his
$ ./test11
The original array is: 1 2 3 4 5
The result is 15
$

 

Get an array value from a function

To pass the array value from the function to the shell script, use the echo command to output all of them and then reassemble them in the script. Let's look at the example below

#!/bin/bash
# returning an array value
function arraydblr {
local origarray
local newarray
local elements
local i
origarray=(`echo "$@"`)
newarray=(`echo "$@"`)
elements=$[ $# - 1 ]
for (( i = 0; i <= $elements; i++ ))
{
newarray[$i]=$[ ${origarray[$i]} * 2 ]
}
echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=`echo ${myarray[*]}`
result=(`arraydblr $arg1`)
echo "The new array is: ${result[*]}"

if run this
$ ./test12
The original array is: 1 2 3 4 5
The new array is: 2 4 6 8 10

 

6. Recursive functions

A recursive function is a function in which a function calls itself again and uses it. One of the typical uses is often used in factorial calculations. Let's take a look at an example of factorial .

#!/bin/bash
# using recursion
function factorial {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[ $1 - 1 ]
local result=`factorial $temp`
echo $[ $result * $1 ]
fi
}
read -p "Enter value: " value
result=`factorial $value`
echo "The factorial of $value is: $result"

if runt this
$ ./test13
Enter value: 5
The factorial of 5 is: 120
$

 

7. Create a library

In order to reduce the same code in the same script, it is used as a method of calling using a function. You can use it without the need to write a script. ​ To use the library, first create the library file to be used first. For example, let's make the following library for arithmetic operations.

 

To use the library, first create the library file to be used first. For example, let's make the following library for arithmetic operations.

# my script functions
function addem {
echo $[ $1 + $2 ]
}
function multem {
echo $[ $1 * $2 ]
}
function divem {
if [ $2 -ne 0 ]
then
echo $[ $1 / $2 ]
else
echo -1
fi
}

 

Let's take a look at an example of using the above library file in a script.

#!/bin/bash
# using a library file the wrong way
./myfuncs ==>call the above library
result=`addem 10 15` ==> Call the library's addem function


echo "The result is $result"
$ ./badtest4
./badtest3: addem: command not found
The result is
$
==> The result is not executed. The reason is that if you execute myfunc within the script, another shell opens and executes myfunc, so you cannot call the function in the current shell.

 

So how can we use functions from other files in this case? There is a way to do that using the source command. The source command does not run the script in a new shell, but executes the file in the currently running script. The way to use the source command is to add a dot (.) in front of the script to be executed. Let's take a look at the example below.

#!/bin/bash
# using functions defined in a library file
. ./myfuncs
value1=10
value2=5
result1=`addem $value1 $value2`
result2=`multem $value1 $value2`
result3=`divem $value1 $value2`
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
echo "The result of dividing them is: $result3"

if run this
$ ./test14
The result of adding them is: 15
The result of multiplying them is: 50
The result of dividing them is: 2
$

 

8. Using functions from the command line

Creating functions from the command line.

Since the shell interprets commands as if they were entered by the user, you can define functions directly on the command line. ​

 

1) The first method is to define all functions in one line as shown below.

$ function divem { echo $[ $1 / $2 ]; }
$ divem 100 5
20

 

When entering a function from the command line, a semicolon (;) must be entered between commands.

$ function divem { echo $[ $1 / $2 ]; }
$ divem 100 5
20

 

2) The second method is to divide the input into several lines.

$ function multem {
> echo $[ $1 * $2 ]
> }
$ multem 3 4
12

 

3) Defining functions in .bashrc file

In the method described above, the corresponding function disappears when exiting the shell. For this purpose, if you define it in the .bashrc file, the .bashrc file is loaded every time the shell is executed, so you can continue to use the functions defined in the file without a separate

Basic functions for each user are defined in the user's home directory. In this file, you can use it by defining the last part as shown below.

$ cat .bashrc
# .bashrc
# Source global definitions
if [ -r /etc/bashrc ]; then
. /etc/bashrc
fi
function addem {
echo $[ $1 + $2 ]
}
$

 

4) Creating a sourcing function file

Just like a shell script, you can use the source command to add from a library file to a .bash file. Please see the example below.

# .bashrc
# Source global definitions
if [ -r /etc/bashrc ]; then
. /etc/bashrc
fi
. /home/rich/libraries/myfuncs
==> Show the dot that is the source command and show the full path where the library
is locatedsource
$

 

If defined here, it can be used automatically in child shell scripts.

 

728x90
반응형

'Shell Script' 카테고리의 다른 글

14 Introduction sed and gawk  (1) 2022.08.27
13 Using Graphic in Script  (1) 2022.08.17
11 Script Control  (0) 2022.08.15
10 Data Expression  (2) 2022.08.13
9. User data input processing  (1) 2022.08.13