详解shell脚本(三)——基础篇下

数组和关联数组

#打印数组长度
echo ${#array_var[*]}
#定义关联数组
declare -A ass_array
ass_array=([index1]=val1 [index2]=val2)#赋值1
ass_array[index1]=val1#赋值2
echo ${!array_var[*]}#打印数组的索引

使用别名

#可以按照下面的方式创建一个别名
alias new_command='command sequence'
alias install='sudo apt-get install'#example
#alias的作用是暂时的,关闭终端后会失效,要让别名一直保持作用,可以将它放入~/.bashrc文件中,因为每当一个新的shell进程生成时,都会执行~/.bashrc中的命令
echo 'alias cmd="command seq"' >> ~/.bashrc
#删除别名,把对应语句从~/.bashrc中删除,或者用unalias.或者使用alias example=,这会取消名为example的别名
#对别名进行转义
\command

终端命令处理

tput和stty是两款终端处理工具。

tput cols 打印列数 tput lines 打印终端行数

tuput longname打印当前终端名

tput cup 100 100 把光标移动到坐标(100,100)处

tputsetb n 设置终端背景色 n在0到7之间

tput bold 设置粗体 tput smul设置下划线的起 tput rmul 设置下划线的止

tput ed 删除从当前光标位置到行尾的所有内容

#输入密码时不显示密码
#!/bin/sh
echo -e "Enter password: "
stty -echo      #选项-echo 禁止将输出发送到终端
read password
stty echo       #选项 echo 允许发送输出
echo
echo Password read.

时间与延时

获取时间date

#打印纪元时
date +%s
date --date "Thu Nov 18 08:0721 IST 2010" +%s #转化为纪元时
date --date "Jan 20 2001" +%A #给的日期是星期几
date "+%d %B %Y"  #按格式输出时间
date -s "格式化的日期字符串"  #设置日期和时间

#检查一组命令所花费的时间
#!/bin/bash
start=$(date +%s)
commands;
statements;

end=$(date+%s)
difference=$((end - start))
echo Time taken to execute commands is $difference seconds.
#另一种方法则是使用time<scriptpath>来得到执行脚本所花费的时间

#! /bin/bash
# 在脚本中生成延时
echo -n Count:
tput sc         #储存光标位置

count=0;
while true;
do
    if [ $count -lt 40 ];
    then 
        let count++;
        sleep 1;
        tput rc     #恢复光标位置
        tput ed     #清除当前光标位置到行尾之间的内容
        echo -n $count;
    else exit 0;
    fi
done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值