hellopasswd
functions in the shell
- A function is to organize a piece of code into a small unit, and give this small unit a name. When using this code, you can directly call the name of this small unit in the format: function f_name(){ command } The function must put on the front
- Example 1 #!/bin/bash input(){ echo $1 $2 $# $0 }
input 1 a b
[root@localhost shell]# vi 1.sh
1 #!/bin/bash
2 function inp(){
3 echo $1 $2 $3 $0 $#
4 }
5
6 inp 1 a 2
[root@localhost shell]# sh 1.sh
1 a 2 1.sh 3
[root@localhost shell]# vi 1.sh
1 #!/bin/bash
2 function inp(){
3 echo "This number 1 is $1"
4 echo "This number 2 is $2"
5 echo "This number 3 is $3"
6 echo "This number 4 is $0"
7 echo "This number 5 is $#"
8 }
9
10 inp b a 2 3 abc
[root@localhost shell]# sh 1.sh
This number 1 is b
This number 2 is a
This number 3 is 2
This number 4 is 1.sh
This number 5 is 5
[root@localhost shell]# vi 1.sh
1 #!/bin/bash
2 function inp(){
3 echo "This number 1 is $1"
4 echo "This number 2 is $2"
5 echo "This number 3 is $3"
6 echo "This number 4 is $0"
7 echo "This number 5 is $#"
8 }
9
10 inp $1 $2 $3
[root@localhost shell]# sh 1.sh 1
This number 1 is 1
This number 2 is
This number 3 is
This number 4 is 1.sh
This number 5 is 1
[root@localhost shell]# sh 1.sh 1 a b
This number 1 is 1
This number 2 is a
This number 3 is b
This number 4 is 1.sh
This number 5 is 3
- Example 2 #!/bin/bash sum(){ s=$[$1+$2] echo $s } sum 1 2
[root@localhost shell]# vi 1.sh
1 #!/bin/bash
2 sum(){
3 s=$[$1+$2]
4 echo $s
5 }
6
7 sum 1 10
[root@localhost shell]# sh 1.sh
11
- Example 3
#!/bin/bash ip(){ ifconfig | grep -A1 "$1" | tail -1 | awk '{print $2}' | awk -F':' '{print $2}' } read -p "Please input eth name:" e myip=ip $e
echo "$e addreass is $myip"
[root@localhost shell]# ifconfig
eno16777736: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.81.130 netmask 255.255.255.0 broadcast 192.168.81.255
inet6 fe80::20c:29ff:fea5:5a89 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:a5:5a:89 txqueuelen 1000 (Ethernet)
RX packets 3802 bytes 348661 (340.4 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2490 bytes 315746 (308.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 0 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
[root@localhost shell]# ifconfig | grep -A1 "eno16777736:\ " | awk '/inet/ {print $2}'
192.168.81.130
[root@localhost shell]# vi 1.sh
1 #!/bin/bash
2 ip(){
3 ifconfig | grep -A1 "$1" | awk '/inet/ {print $2}'
4 }
5
6 read -p "Please input the eth name: " eth
7 ip $eth
[root@localhost shell]# sh 1.sh
Please input the eth name: eno16777736
192.168.81.130
Determine whether there is a network card, and then determine whether the network card has an ip
Modified on 180228