cszer

shell中数组的用法

分类: shell       评论: 0   阅读:1,898 views

shell中数组的定义:
命令法 array=($(ls /))
列举法 array=(1 2 3)

array=(
red
blue
green
)

列出数组中所有元素:
echo ${array[#]}

echo ${array[@]}

列出数组的长度 :
echo ${#array[#]}

echo ${#array[@]}

循环列出数组中的元素:

1
2
3
4
for i in ${array[#]}
do
     echo $i
done

1
2
3
4
for ((i=0;i<echo ${#array[#]};i++))
do
     echo ${array[$i]}
done

实例:关闭系统不需要的服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/bash
services=(
acpid
anacron
atd
cpuspeed
crond
gpm
haldaemon
iptables
irqbalance
lm_sensors
messagebus
microcode_ctl
network
sshd
syslog
xfs
)
 
for list in ${services[@]}
do
     chkconfig --level 235 $list on
done
 
services_tmp=`echo ${services[*]} | tr ' ' '|'`
 
no_services_tmp=(`chkconfig --list | grep 0: | awk -F' ' '{print $1}' | grep -Ev "$services_tmp"`)
 
for list in ${no_services_tmp[@]}
do
     chkconfig --level 235 $list off
done
 
chkconfig --list | grep 3:on

实例:分割字符串存至数组

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
 
str="one,two,three,four"
OLD_IFS="$IFS"
IFS=","
arr=($str)
IFS="$OLD_IFS"
for i in ${arr[@]}
do
	echo "$i"
done

执行脚本输出如下:

one
two
three
four

除非注明,文章皆由( csz )原创,转载请标明本文地址
本文地址: http://www.cszhi.com/20121210/shell-array.html

12-10
2012

发表评论