1.数组和关联数组
数组是shell脚本非常重要的组成部分,它借助索引将多个独立的数据存储为一个集合。普通数组只能使用整数作为数组索引。Bash也支持关联数组,它可以使用字符串作为数组索引。在很多情况下,采用字符串式索引更容易理解,这时候关联数组就派上用场了。
1.1 普通数组实例
1)在单行中使用一列值来定义一个数组
array_var=(1 2 3 4 5 6)
#这些值将会存储在以0为起始索引的连续位置上
2)将数组定义为一组索引值
array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"
array_var[3]="test4"
array_var[4]="test5"
array_var[5]="test6"
3)打印出特定索引的数组元素内容
[lirong@lr ~]# array_var=(1 2 3 4 5 6)
[lirong@lr ~]# echo ${array_var[0]}
1
[lirong@lr ~]# index=5
[lirong@lr ~]# echo ${array_var[$index]}
6
[lirong@lr ~]# echo ${array_var[*]}
1 2 3 4 5 6
4)打印数组长度
[lirong@lr ~]# echo ${#array_var[*]}
6
1.2 关联数组实例
1)定义关联数组
[lirong@lr ~]# declare -A fruits_value
[lirong@lr ~]# fruits_value=([apple]='100 dollars' [orange]='150 dollars')
[lirong@lr ~]# echo "Apple costs ${fruits_value[apple]}"
Apple costs 100 dollars
[lirong@lr ~]# echo "orange costs ${fruits_value[orange]}"
orange costs 150 dollars
2)列出数组索引
[lirong@lr ~]# echo ${!fruits_value[*]}
orange apple
2.使用别名
1)按照下面的方式创建一个别名
alias la='ls -A'
这样一来,使用la代替ls -A,alias命令的作用是暂时的。一旦关闭当前终端,所有设置过的别名就失效了。可以将它放入~/.bashrc文件中。因为每当一个新的shell进程生成时,都会执行~/.bashrc中的命令。
echo 'alias la="ls -A"' >>~/.bashrc
2)删除别名
unalias la
3)创建别名时,如果已经由同名的别名存在,那么原有的别名设置将会被新的设置取代。
3.获取终端信息
1)获取终端的行数和列数
[lirong@lr ~]# tput cols
147
[lirong@lr ~]# tput lines
24
2)打印出当前终端名
[lirong@lr ~]# tput longname
X11 terminal emulator
3)将光标移动到坐标(100,100)处
tput cup 100 100
4)设置终端背景色
tput setb n
其中n可以在0-7之间。
5)设置文本前景色
tput setf n
其中n可以在0-7之间。
6)设置文本样式为粗体
tput bold
7)设置下划线的起止
tput smul
tput rmul
4.时间和日期
1)读取日期
[lirong@lr ~]# date
Tue Nov 28 15:06:03 CST 2017
2)打印纪元时
[lirong@lr ~]# date +%s
1511852861
3)用格式串结合+作为date命令的参数,可按照自己的选择打印出对应格式的日期
[lirong@lr ~/work_lr/mygit/shell]# date "+%d %B %Y"
28 November 2017
[lirong@lr ~/work_lr/mygit/shell]# date "+%d %b %Y"
28 Nov 2017
4)设置日期时间
date -s "21 June 2014 11:01:01"
2017-11-28-LR Linux shell脚本攻略