天天看點

[Shell學習筆記] 數組、關聯數組和别名使用

[Shell學習筆記] 數組、關聯數組和别名使用

文章目錄

[隐藏]

  • 數組
  • 關聯數組
  • 使用别名

數組作為一種特殊的資料結構在任何一種程式設計語言中都有它的一席之地,數組在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開始被引入,關聯數組的索引值可以使用任意的文本。關聯數組在很多操作中很有用。更新bash請看這裡《shell更新,Linux系統更新bash》

關聯數組的聲明:

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