shell 学习笔记 数组&date的使用

摘自 Linux Shell 脚本攻略 第一章 小试牛刀

数组

数组的定义

  1. 单行中使用数值列表来定义一个数组
array_var=(test1 test2 test3 test4)
  1. 将数组定义成一组“索引-值”
 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

关联数组赋值

  1. 使用行内 “索引-值” 列表
$ ass_array=([index1]=val1 [index2]=val2)
  1. 使用独立的“索引-值”进行赋值:
$ 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值