当前位置:网站首页>Shell learning record (IV)

Shell learning record (IV)

2022-06-26 02:04:00 _ Bruce

Shell function

  • 1、 You can take function fun() Definition , It can also be direct fun() Definition , Without any parameters .
  • 2、 Parameter return , Can display plus :return return , If not , Results will be run with the last command , As return value . return Heel value n(0-255)
#!/bin/bash
funWithReturn(){
        a=1
        b=5
        c=$[$a+$b]
        return $c
}
funWithReturn
echo " The sum of the two numbers entered is  $? !"

Output : The sum of the two numbers entered is 6 !

The return value of the function passes through $? To obtain a .

Be careful : All functions must be defined before use . This means that you have to put the function at the beginning of the script , until shell When the interpreter first discovered it , Can be used . Call a function using only its function name .

Function parameter

stay Shell in , You can pass parameters to a function when you call it . Inside the body of the function , adopt $n To get the value of the parameter , for example ,$1 Represents the first parameter ,$2 Represents the second parameter ...

Examples of functions with arguments :

#!/bin/bash
funWithParam(){
    echo " The first parameter is zero  $1 !"
    echo " The second parameter is  $2 !"
    echo " The tenth parameter is  $10 !"
    echo " The tenth parameter is  ${10} !"
    echo " The eleventh parameter is  ${11} !"
    echo " The total number of parameters is  $#  individual !"
    echo " Output all parameters as a string  $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

Output :

 The first parameter is zero  1 !
 The second parameter is  2 !
 The tenth parameter is  10 !
 The tenth parameter is  34 !
 The eleventh parameter is  73 !
 The total number of parameters is  11  individual !
 Output all parameters as a string  1 2 3 4 5 6 7 8 9 34 73 !

Be careful :$10 Can't get the tenth parameter , Getting the tenth parameter requires ${10}. When n>=10 when , Need to use ${n} To get the parameters .

in addition , There are also a few special characters for processing parameters :

Shell Input / Output redirection Shell

Redirect in-depth explanation

/dev/null file

File contains

Like any other language ,Shell You can also include external scripts . This can easily encapsulate some common code as a separate file .

We can go through .fileName perhaps source fileName Include files

test1.sh The code is as follows :

#!/bin/bash
url="http://www.baidu.com"

test2.sh

#!/bin/bash
# Use  .  Number test1.sh  file 
. ./test1.sh

#  Or use the following include file code 
# source ./test1.sh

echo " Baidu official website address :$url"

And then execute test2.sh

Output :

 Baidu official website address :http://www.baidu.com

 

原网站

版权声明
本文为[_ Bruce]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260023565388.html