一. 函数:
1. shell函数优势:
方式1:function 函数名() {指令return}方式2:function 函数名 {指令return}方式3:函数名 ( ) {指令return}
3. 函数的调用:
function_name param1 param2 …
函数名
函数名 参数
[root@localhost test6]# vim stringLength.sh#!/bin/bashlength(){str=$1result=0if [ "$1" != "" ];thenresult=${#str}fiecho "$result"}length=$(length "abcd")echo "the string's length is $length"[root@localhost test6]# bash length.shthe string's length is 4
方式一:. filename #函数库文件名方式二:source filenamefunction_name [ param1 param2 … ] #调用函数的的方式仍然一样
[root@localhost test6]# vim fact.sh#!/bin/bashfact(){local n="$1"if [ "$n" -eq 0 ]thenresult=1elselet "m=n-1"fact "$m"echo "result=$n * $result"fi}fact "$1" #表示将脚本的第一个参数作为函数的第一个参数传递进函数echo "Factorial of $1 is $result"[root@localhost test6]# bash fact.sh 0Factorial of 0 is 1[root@localhost test6]# bash fact.sh 5Factorial of 5 is 120
[root@localhost test6]# cat variable.sh#!/bin/bashvar="hello world"var2="haha"func(){local var="orange"echo "$var"local var2="hello"echo "$var2"}echo "$var"funcecho "$var"echo "$var2"[root@localhost test6]# bash variable.shhello worldorangehellohello worldhaha
二. 数组:
1. 定义普通数组 :
方法一:用小括号将变量值括起来赋值给数组变量,每个变量之间要用空格进行分隔。
array=(value1 value2 value3 ... )
array=([0]=one [1]=two [2]=three ... [n]=valuen)
方法三:分别定义数组变量的值。
array[0]=a;array[1]=b;array[2]=c
方法四:动态的定义变量,并使用命令的输出结果作为数组的内容。
array=( $( 命令 ) ) / array=( ` 命令 ` )
方法五:通过declare语句定义数组。
declare -a array
2. 定义关联数组:关联数组使用字符串作为下标( 索引 ),而不是整数,这样可以做到见名知意。不同于普通数组,关联数组必须使用带有 -A 选项的 declare 命令创建。
方法一:一次赋一个值。
[root@localhost ~]# declare -A array[root@localhost ~]# array[shuju1]=apple[root@localhost ~]# array[shuju2]=banana[root@localhost ~]# echo ${array[*]}banana apple
方法二:一次赋多个值 。
[root@localhost ~]# declare -A array[root@localhost ~]# array=([index1]=tom [index2]=jack [index3]=alice)[root@localhost ~]# echo ${array[@]}tom jack alice
3. 数组操作 :
1>. 获取所有元素:
echo ${array[*]} # *和@ 都是代表所有元素
2>. 获取元素下标:
echo ${!array[@]}echo ${!array[*]}
3>. 获取数组长度:
echo ${#array[*]}echo ${#array[@]}
4>. 获取第一个元素:
echo ${array[0]}
5>. 添加元素:
array[newIndex]=要添加的值
6>. 添加多个元素:
array+=(值1 值2 值3)
7>. 以切片方式获取部分数组元素:(用户得到的是一个空格隔开的多个元素值组成的字符串) 。
${array[@ | *] : start : length}
8>. 删除第一个元素:
unset array[0] # 删除会保留元素下标
9>. 删除数组:
unset array
4. 遍历数组:
方法 1:#!/bin/bashIP=(192.168.1.1 192.168.1.2 192.168.1.3)for ((i=0;i<${#IP[*]};i++)); doecho ${IP[$i]} # " i "表示的是数组的索引donebash test.sh192.168.1.1192.168.1.2192.168.1.3方法 2:#!/bin/bashIPList=(192.168.1.1 192.168.1.2 192.168.1.3)for IP in ${IPList[*]}; doecho $IP #" IP "表示的是数组的内容done

被折叠的 条评论
为什么被折叠?



