Linux Shell 數(shù)組建立及使用技巧
linux shell在編程方面比windows 批處理強(qiáng)大太多,無(wú)論是在循環(huán)、運(yùn)算。已經(jīng)數(shù)據(jù)類(lèi)型方面都是不能比較的。 下面是個(gè)人在使用時(shí)候,對(duì)它在數(shù)組方面一些操作進(jìn)行的總結(jié)。
1.數(shù)組定義
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo $a
一對(duì)括號(hào)表示是數(shù)組,數(shù)組元素用“空格”符號(hào)分割開(kāi)。
2.數(shù)組讀取與賦值
得到長(zhǎng)度:
[chengmo@centos5 ~]$ echo ${
#a[@]}
用${#數(shù)組名[@或*]} 可以得到數(shù)組長(zhǎng)度
讀?。?/p>
[chengmo@centos5 ~]$ echo ${a[2]}
3
[chengmo@centos5 ~]$ echo ${a[*]}
1 2 3 4 5
用${數(shù)組名[下標(biāo)]} 下標(biāo)是從0開(kāi)始 下標(biāo)是:*或者@ 得到整個(gè)數(shù)組內(nèi)容
賦值:
[chengmo@centos5 ~]$ a[1]=100
[chengmo@centos5 ~]$ echo ${a[*]}
1 100 3 4 5
[chengmo@centos5 ~]$ a[5]=100
[chengmo@centos5 ~]$ echo ${a[*]}
1 100 3 4 5 100
直接通過(guò) 數(shù)組名[下標(biāo)] 就可以對(duì)其進(jìn)行引用賦值,如果下標(biāo)不存在,自動(dòng)添加新一個(gè)數(shù)組元素
刪除:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a
[chengmo@centos5 ~]$ echo ${a[*]}
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ unset a[1]
[chengmo@centos5 ~]$ echo ${a[*]}
1 3 4 5
[chengmo@centos5 ~]$ echo ${
#a[*]}
4
直接通過(guò):unset 數(shù)組[下標(biāo)] 可以清除相應(yīng)的元素,不帶下標(biāo),清除整個(gè)數(shù)據(jù)。
3.特殊使用
分片:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo ${a[@]:0:3}
1 2 3
[chengmo@centos5 ~]$ echo ${a[@]:1:4}
2 3 4 5
[chengmo@centos5 ~]$ c=(${a[@]:1:4})
[chengmo@centos5 ~]$ echo ${
#c[@]}
4
[chengmo@centos5 ~]$ echo ${c[*]}
2 3 4 5
直接通過(guò) ${數(shù)組名[@或*]:起始位置:長(zhǎng)度} 切片原先數(shù)組,返回是字符串,中間用“空格”分開(kāi),因此如果加上”()”,將得到切片數(shù)組,上面例子:c 就是一個(gè)新數(shù)據(jù)。
替換:
[chengmo@centos5 ~]$ a=(1 2 3 4 5)
[chengmo@centos5 ~]$ echo ${a[@]/3/100}
1 2 100 4 5
[chengmo@centos5 ~]$ echo ${a[@]}
1 2 3 4 5
[chengmo@centos5 ~]$ a=(${a[@]/3/100})
[chengmo@centos5 ~]$ echo ${a[@]}
1 2 100 4 5
調(diào)用方法是:${數(shù)組名[@或*]/查找字符/替換字符} 該操作不會(huì)改變?cè)葦?shù)組內(nèi)容,如果需要修改,可以看上面例子,重新定義數(shù)據(jù)。
以上內(nèi)容是小編給大家介紹的linux shell 數(shù)組建立及使用技巧,希望對(duì)大家有所幫助。
- Linux shell腳本編程if語(yǔ)句的使用方法(條件判斷)
- Linux系統(tǒng)中bash shell編程的10個(gè)基礎(chǔ)問(wèn)題講解
- linux shell 管道命令(pipe)使用及與shell重定向區(qū)別
- linux shell數(shù)據(jù)重定向(輸入重定向與輸出重定向)詳細(xì)分析
- linux shell實(shí)現(xiàn)隨機(jī)數(shù)幾種方法分享(date,random,uuid)
- linux shell命令快捷獲得系統(tǒng)幫助(一)[man-pages定義規(guī)范]
- linux shell 字符串操作(長(zhǎng)度,查找,替換)詳解
- Linux shell編程中IO和條件及循環(huán)處理的細(xì)節(jié)問(wèn)題討論
相關(guān)文章
shell腳本編寫(xiě)ping包及arp的監(jiān)控并發(fā)送短信功能
這篇文章主要介紹了shell腳本編寫(xiě)ping包及arp的監(jiān)控并發(fā)送短信功能,需要的朋友可以參考下2017-03-03
shell腳本自動(dòng)檢測(cè)網(wǎng)絡(luò)掉線和自動(dòng)重連
這篇文章主要介紹了shell腳本自動(dòng)檢測(cè)網(wǎng)絡(luò)掉線和自動(dòng)重連,這篇文章介紹的是自動(dòng)檢測(cè)連接網(wǎng)絡(luò)的解決方法,需要的朋友可以參考下2019-12-12
使用ubuntu搭建公網(wǎng)個(gè)人郵件服務(wù)器(基于postfix,dovecot,mysql)
這篇文章主要介紹了基于ubuntu搭建公網(wǎng)個(gè)人郵件服務(wù)器(基于postfix,dovecot,mysql),免費(fèi)的郵箱每天發(fā)信數(shù)量是有限制的,所以呢就想著搭建一個(gè)自己的郵件服務(wù)器,需要的朋友可以參考下2019-06-06
linux下監(jiān)控網(wǎng)絡(luò)流量的腳本
在我們的日常工作當(dāng)中,監(jiān)控網(wǎng)絡(luò)要么使用iptarf,ifstat這些命令實(shí)現(xiàn)的,但是需要裝額外的RPM包。特別是iptarf裝起來(lái)麻煩2013-01-01

