数组、关联数组和别名使用
数组作为一种特殊的数据结构在任何一种编程语言中都有它的一席之地,数组在Shell脚本中也是非常重要的组成部分,它借助索引将多个独立的数据存储为一个集合。
数组
普通数组只能使用整数作为数组的索引值。
定义数组
格式:array[key]=value
单行一列值:
array_pt=( 1 2 3 4 5 6 )
一组索引值:
array_pt[0]="text1"
array_pt[1]="text2"
array_pt[2]="text3"
array_pt[3]="text4"
array_pt[4]="text5"
array_pt[5]="text6"
打印数组
打印指定索引的数组元素内容:
#echo ${array_pt[0]}
text1
index=3
#echo ${array_pt[$index]}
text4
打印数组中的所有值:
#echo ${array_pt[*]}
或者
#echo ${array_pt[@]}
打印数组长度(即数组中元素的个数):
#echo ${#array_pt[*]}
删除数组:
unset array_pt[1] //删除数组中第一个元素
unset array_pt //删除整个数组
数组的提取:
例如定义了数组 array=( [0]=one [1]=two [2]=three [3]=four )
${array[@]:0} //除去所有元素
${array[@]:1} //出去第一个元素后的所有元素
#echo ${array[@]:0:2}
one two
#echo ${array[@]:1:2}
two three
子串删除:
#echo ${array[@]:0}
one two three four
左边开始最短的匹配:"t*e"
,这将匹配到"thre"
#echo ${array[@]#t*e}
one two e four
左边开始最长的匹配,这将匹配到"three"
#echo ${array[@]##t*e}
从字符串的结尾开始最短的匹配
#echo ${array[@]%o}
one tw three four
从字符串的结尾开始最长的匹配
# echo ${array[@]%%o}
one tw three four
子串替换:
#echo ${array[@]/o/m}
mne twm three fmur
没有指定替换子串,则删除匹配到的子符
#echo ${array[@]//o/}
ne tw three fur
替换字符串前端子串
#echo ${array[@]/#o/k}
kne two three four
替换字符串后端子串
#echo ${array[@]/%o/k}
one twk three four
关联数组
关联数组从bash 4.0开始被引入,关联数组的索引值可以使用任意的文本。关联数组在很多操作中很有用。
关联数组的声明:
declare -A array_var
使用内嵌索引-值列表法将元素添加到关联数组:
array_var=( [one]=one-1 [two]=two-2 [three]=three-3 [four]=four-4 [five]=five-5 [six]=six-6 )
使用独立的索引-值进行赋值:
array_var[one]=one-1
array_var[two]=two-2
array_var[three]=three-3
array_var[four]=four-4
array_var[five]=five-5
array_var[six]=six-6
关联数组的打印方法跟普通数组用法一样。
列出数组索引值:
#echo ${!array_var[*]}
four one five six two three
列出索引值的方法也可以用在普通数组上。
别名
别名就是提供一种便捷的方式来完成某些长串命令的操作。省去不必要的麻烦,提高效率。一般可以是函数或者alias命令
来实现。
alias举例
alias nginxrestart='/usr/local/webserver/nginx/sbin/nginx -s reload'
这样设置之后以后可以使用nginxrestart这个命令来代替/usr/local/webserver/nginx/sbin/nginx -s reload
了。这样设置重启之后就会失效,所以需要将它放入~/.bashrc
文件中。
echo 'alias nginxrestart="/usr/local/webserver/nginx/sbin/nginx -s reload"' >> ~/.bashrc
查看系统已经定义的别名
[root@mail text]# alias
alias cp='cp -i'
alias l.='ls -d .* --color=tty'
alias ll='ls -l --color=tty'
alias ls='ls --color=tty'
alias mv='mv -i'
alias rm='rm -i'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
别名转义
有些命令不是总是希望使用别名,可以在命令之前输入反斜杠\
来忽略所定义过的别名。
#\command