一、数组
1、数组遍历
#!/bin/bash
SUPPORTED_OPENSTACK_VERSION=('libtery' 'mitaka' 'ocata')
for var in ${SUPPORTED_OPENSTACK_VERSION[@]}
do
echo $var
done
运行结果
root@vSOM:~# ./test.sh
libtery
mitaka
ocata
2、判断元素是否在数组中
#!/bin/bash
OPENSTACK_VERSION=('libtery' 'mitaka' 'ocata')
echo "please input openstack version:"
read version
if [[ "${OPENSTACK_VERSION[@]}" =~ ${version} ]]; then
echo "$version in vesion array"
else
echo "$version not in version array"
fi
运行结果
root@vSOM:~# ./test.sh
please input openstack version:
mitaka
mitaka in vesion array
root@vSOM:~# ./test.sh
please input openstack version:
juno
juno not in version array
3、数组实现菜单选择
#!/bin/bash
SUPPORTED_OPENSTACK_VERSION=('libtery' 'mitaka' 'ocata')
echo "Please choose openstack version:"
select var in ${SUPPORTED_OPENSTACK_VERSION[@]};do
echo "selected version:$var"
break
done
运行结果
root@vSOM:~# ./test.sh
Please choose openstack version:
1) libtery
2) mitaka
3) ocata
#? 2
selected version:mitaka
4、字符转换成数组
#!/bin/bash
SUPPORTED_OPENSTACK_VERSION_STR='libtery mitaka ocata'
SUPPORTED_OPENSTACK_VERSION_ARRAY=($SUPPORTED_OPENSTACK_VERSION_STR)
for var in ${SUPPORTED_OPENSTACK_VERSION_ARRAY[@]}
do
echo $var
done
运行结果
root@vSOM:~# ./test.sh
libtery
mitaka
ocata
如果字符串的分隔符不是空格,可以将IFS设置成相应的分隔符,再转成数组,如下所示:
#!/bin/bash
SUPPORTED_OPENSTACK_VERSION_STR='libtery;mitaka;ocata'
IFS=";"
SUPPORTED_OPENSTACK_VERSION_ARRAY=($SUPPORTED_OPENSTACK_VERSION_STR)
for var in ${SUPPORTED_OPENSTACK_VERSION_ARRAY[@]}
do
echo $var
done
运行结果同上
二、字典
1、字典的定义和使用
declare -A NEUTRON_AGENT_SUPPORTED_VERSION
NEUTRON_AGENT_SUPPORTED_VERSION=([libtery]='7.2.0' [mitaka]='8.3.0' [ocata]='10.0.1')
echo "${NEUTRON_VERSION[mitaka]}"
运行结果
root@vSOM:~# ./test.sh
8.3.0
三、字符串
1、分割字符串
#!/bin/bash
OPENSTACK_VERSION_STR='libtery;mitaka;ocata'
echo $OPENSTACK_VERSION_STR | cut -d ';' -f1
echo $OPENSTACK_VERSION_STR | cut -d ';' -f3
运行结果
root@vSOM:~# ./test.sh
libtery
ocata
也可以用下面的方法
#!/bin/bash
OPENSTACK_VERSION_STR='libtery;mitaka;ocata'
echo $OPENSTACK_VERSION_STR | awk -F ';' '{print $1}'
echo $OPENSTACK_VERSION_STR | awk -F ';' '{print $3}'
运行结果同上
原文链接:https://www.f2er.com/bash/391411.html