文章目录
一、Shell函数
将命令序列按格式写在一起;可方便重复使用命令序列
shell函数定义
[function] 函数名(){
命令序列
[return x]
}
基本格式如上,其中【function】是可选项,表示该函数的功能,这个是可以省略的;函数名后面加(),里面没有内容;执行的命令放入{}里;[return x]的作用是当命令序列执行完毕后返回系统的值;也可以省略
示例:
1、将上面的格式带入,先定义函数在调用函数,必须在函数后面调用
[root@localhost ~]# vim hanshu.sh
#!/bin/bash
function hello(){
echo hello
}
hello
[root@localhost ~]# bash hanshu.sh
hello
2、用定义函数输入hello、world、nihao中,将nihaio的执行为hello world,需要加入反撇号
[root@localhost ~]# vim hanshu.sh
#!/bin/bash
function hello(){
echo hello
}
world(){
echo world
}
nihao(){
echo `hello` `world` #输入执行的将加入反撇号
}
nihao #调用的函数
[root@localhost ~]# bash hanshu.sh
hello world #执行的结果
二、求和算数
1、将用定义函数的格式,进行算数的方法
[root@localhost ~]# vim hanshu.sh
#!/bin/bash
SUM(){
let sum=$1+$2
echo $sum
}
SUM 5 6
[root@localhost ~]# bash hanshu.sh
11
2、第二种方法,使数值更为灵活使用
[root@localhost ~]# vim hanshu.sh
#!/bin/bash
SUM(){
let sum=$1+$2
echo $sum
}
SUM $1 $2 #将这里设置成$1 $2之后在命令行当中输入想要算的数字就可以
[root@localhost ~]# bash hanshu.sh 1 2
3
[root@localhost ~]# bash hanshu.sh 45 45
90
三、数组
1、数组定义方法
1.1方法一
[root@localhost ~]# a=([0]=1 [1]=2 [2]=3 [3]=4)
[root@localhost ~]# echo ${a[*]}
1 2 3 4
1.2方法二
[root@localhost ~]# b=(1 2 3 4)
[root@localhost ~]# echo ${a[*]}
1 2 3 4
1.3方法三
[root@localhost ~]# c="1 2 3 4"
[root@localhost ~]# d=($c)
[root@localhost ~]# echo ${d[*]}
1 2 3 4
1.4方法四
[root@localhost ~]# e[0]=1
[root@localhost ~]# e[1]=2
[root@localhost ~]# e[2]=3
[root@localhost ~]# e[3]=4
[root@localhost ~]# echo ${e[*]}
1 2 3 4
2、数组操作
2.1元素切片
${数组名[*]:起始位置:长度}
[root@localhost ~]# echo ${a[*]:0:1}
1
2.2元素替换
[root@localhost ~]# echo ${a[*]/2/12}
1 12 3 4
2.3元素删除
[root@localhost ~]# echo ${a[*]/2/12}
1 12 3 4
[root@localhost ~]# unset a[1]
[root@localhost ~]# echo ${a[*]}
1 3 4
3、冒泡法排序
[root@localhost ~]# vim hanshu.sh
#!/bin/bash
a=(10 20 40 70 50)
for ((i=0;i<${#a[*]};i++))
do
for ((j=0;j<${#a[*]}-$i;j++))
do
if [ ${a[j]} -gt ${a[j+1]} ];then
b=${a[j]}
a[j]=${a[j+1]}
a[j+1]=$b
fi
done
done
echo ${a[*]}
[root@localhost ~]# bash hanshu.sh
10 20 40 50 70
4、将数组中达不到60的数值删除
[root@localhost ~]# vim ssh.sh
#!/bin/bash
a=(10 20 30 40 50 60 70 80 90)
b=${#a[*]}
for ((i=0;i<$b;i++))
do
if [ ${a[i]} -lt 60 ];then
unset a[i]
fi
done
echo ${a[*]}
[root@localhost ~]# bash ssh.sh
60 70 80 90