- 计算两个参数的和
- 获取字符串的长度
- 将一个点分十进制格式的IP地址转换成点分二进制格式。比如 255.255.255.255 --> 11111111.11111111.11111111.11111111
- 写一个脚本,判断给定的 IP 地址范围[192.168.72.130 ~ 192.168.72.140]是否在线
计算两个参数的和
[root@openEuler ~]# cat fun2.sh
#!/bin/bash
sum1() {
sum=$[$1 + $2]
echo $sum
}
read -p "Please enter first number: " first
read -p "Please enter second number: " second
sum1 first second
#或者
res=$(sum1 first second)
echo $res
[root@openEuler ~]# bash fun2.sh
Please enter first number: 6
Please enter second number: 4
10
获取字符串的长度
[root@openEuler ~]# cat fun3.sh
#!/bin/bash
length() {
str=$1
len=0
if [ "$1" != "" ]; then
len=${#str}
fi
return $len
}
length "abc123"
echo "the string's length is $?"
[root@openEuler ~]# bash fun3.sh
the string's length is 6
将一个点分十进制格式的IP地址转换成点分二进制格式。比如 255.255.255.255 --> 11111111.11111111.11111111.11111111
[root@openEuler ~]# cat fun4.sh
#!/bin/bash
decimal_to_bin() {
NUM=$1
for i in {1..8}
do
SUM=$[NUM % 2]$SUM
let NUM/=2
#((NUM=NUM/2))
done
echo $SUM
}
split_ip() {
IP=$1
for i in {1..4}
do
num=${IP%%.*} # IP=192.168.72.150 -> num=192
#echo "num=$num"
IP=${IP#*.} # IP=168.72.150 delete 192
#echo "ip=$IP"
BIN=$(decimal_to_bin num)
#decimal_to_bin $num
echo -n $BIN
done
}
read -p "Please enter a valid IP address: " INIP
res=$(split_ip $INIP)
echo ${res%.*}
[root@openEuler ~]# bash fun4.sh
Please enter a valid IP address: 192.168.72.112
11000000.10101000.01001000.01110000
写一个脚本,判断给定的 IP 地址范围[192.168.72.130 ~ 192.168.72.140]是否在线
[root@openEuler ~]# cat fun5.sh
#!/bin/bash
online() {
for i in {148..152}
do
if ping -c1 192.168.72.$i &>/dev/null
then
echo "192.168.72.$i is up"
else
echo "192.168.72.$i is unknow"
fi
done
}
online
[root@openEuler ~]# bash fun5.sh
192.168.72.148 is unknow
192.168.72.149 is unknow
192.168.72.150 is up
192.168.72.151 is up
192.168.72.152 is unknow