摘自 Linux Shell 脚本攻略 第一章 小试牛刀
数组
数组的定义
- 单行中使用数值列表来定义一个数组
array_var=(test1 test2 test3 test4)
- 将数组定义成一组“索引-值”
array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"
array_var[3]="test4"
array_var[4]="test5"
array_var[5]="test6"
数组的使用
- 打印出特定索引的数组元素内容
echo ${array_var[0]}
test1
index=5
echo ${array_var[$index]}
test6
- 以列表形式打印出数组中的所有值
$ echo ${array_var[*]}
test1 test2 test3 test4 test5 test6
$ echo ${array_var[@]}
test1 test2 test3 test4 test5 test6
- 打印数组长度(即数组中元素的个数)
echo ${#array_var[*]}
6
关联数组
关联数组定义
$ declare -A ass_array
关联数组赋值
- 使用行内 “索引-值” 列表
$ ass_array=([index1]=val1 [index2]=val2)
- 使用独立的“索引-值”进行赋值:
$ ass_array[index1]=val1
$ ass_array[index2]=val2
示例
$ declare -A fruits_value
$ fruits_value=([apple]='100 dollars' [orange]='150 dollars')
$ echo "Apple costs ${fruits_value[apple]}"
Apple costs 100 dollars
列出关联数组的索引
$ echo ${!fruits_value[*]}
orange apple
$ echo ${!fruits_value[@]}
orange apple
对于普通数组,这个方法同样可行
采集终端信息
tput和stty是两款终端处理工具。
- 获取终端的行数和列数
$ tput cols
256
$ tput lines
54
- 打印出当前的终端名
$ tput longname
xterm with 256 colors
获取并设置日期及延时
- 读取时间
$ date
2021年 11月 16日 星期二 14:04:26 CST
- 打印纪元时
$ date +%s
1637042698
- 将日期转换成纪元时
$ date --date "Wed mar 15 08:09:16 EDT 2017" +%s
1489579756
选项–date指定了作为输入的日期。我们可以使用任意的日期格式化选项来打印输出
$ date --date "Jan 20 2001" +%A
星期六
data命令可以根据指定的日期找出这一天是星期几
- 格式化输出
$ date "+%d %B %Y"
16 十一月 2021