shell编程系列4--有类型变量:字符串、只读类型、整数、数组
有类型变量总结:
declare命令和typeset命令两者等价
declare、typeset命令都是用来定义变量类型的
declare命令参数总结
1.declare -r 将变量设置为只读类型
declare -r var="hello"
var="world"
# 变量默认可以修改
[root@es01 shell]# var2="hello world"
[root@es01 shell]# var2="hello python"
[root@es01 shell]# echo $var2
hello python
# 声明为只读变量,就不可修改
[root@es01 shell]# declare -r var2
[root@es01 shell]# var2="hello java"
-bash: var2: readonly variable
2. declare -i 将变量设为整数
# 默认把变量当做字符处理
[root@es01 shell]# num1=10
[root@es01 shell]# num2=$num1+20
[root@es01 shell]# echo $num2
10+20
# 声明为整数
[root@es01 shell]# declare -i num3
[root@es01 shell]# num3=$num1+90
[root@es01 shell]# echo $num3
100
3.declare -a 将变量定义为数组
# 定义数组
[root@es01 shell]# declare -a array
[root@es01 shell]# array=("jones" "make" "kobe" "jordan")
# 列出数组所有元素
[root@es01 shell]# echo ${array[@]}
jones make kobe jordan
[root@es01 shell]# echo ${array[1]}
make
[root@es01 shell]# echo ${array[0]}
jones
[root@es01 shell]# echo ${array[2]}
kobe
# 数组长度
[root@es01 shell]# echo ${#array[@]}
4
# 输出数组中元素长度
[root@es01 shell]# echo ${#array[0]}
5
[root@es01 shell]# echo ${#array[1]}
4
-f 显示此脚本前定义过的所有函数和内容
-F 进显示脚本前定义过的函数名
数组常用的方法(仅供参考,实际生产用的少)
array=("jones" "mike" "kobe" "jordan")
输出数组内容:
echo ${array[@]} 输出全部内容
echo ${array[1]} 输出下标索引为1的内容
获取数组长度:
echo ${#array} 数组内元素个数
echo ${#array[2]} 数组内下标索引为2的元素长度
给数组某个下标赋值:
array[0]="lily" 给数组下标索引为1的元素赋值为lily
array[20]="hanmeimei" 在数组尾部添加一个新元素
删除元素:
unset array[2] 清空元素
unset array 清空整个数组
分片访问:
${array[@]:1:4} 显示数组下标索引从1开始到3的3个元素
内容替换:
${array[@]/an/AN} 将数组中所有元素包含an的子串替换为AN
数组遍历:
for v in ${array[@]}
do
echo $v
done
4.declare -x 将变量声明为环境变量
[root@es01 shell]# num5=30
[root@es01 shell]# echo $num5
30
[root@es01 shell]# vim test1.sh
[root@es01 shell]# cat test1.sh
#!/bin/bash
#
echo $num5
# 在脚本中直接使用shell环境中定义的变量是无法引用的
[root@es01 shell]# sh test1.sh
# 当使用declare -x 变量后,就可以直接在脚本中引用了
[root@es01 shell]# declare -x num5
[root@es01 shell]# sh test1.sh
30
declare +r 取消一个变量