Linux_Shell脚本攻略学习笔记(2)1.6-1.15

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25453065/article/details/85453351

1.6
1)数组的类别:
a.普通数组,索引是数字,从0开始,但是特别的是,索引可以不连续
b.关联数组,索引是字符串
shell 中的数组更像是key-value的感觉,就算是普通数组,也没有必须连续。用起来还是很方便。
2)定义数组的方法:
a.普通数组:

  • arr=(1 3 5)
  • arr[1]=3 arr[3]=5

b.关联数组:
第一步:先声明 declare -A arr
第二步:

  • arr=([first]=‘1’ [last]=‘10’)
  • arr[first]=1 arr[second]=hello

3)数组的特殊用法
a.访问某一个元素:echo ${arr[1]}
b.遍历数组,全部打印: echo ${arr[*]} echo ${arr[@]}
c.打印数组的长度:echo ${#arr[*]}
d.列出数组的索引值: echo ${!arr[*]}

1.7
1)别名的定义方法:(删除使用unalias)
alias install=‘sudo apt-get install’
2)别名的命令作用只在当前终端有效,为了长期有效,可以将其写入 ~/.bashrc中。
echo ‘alias install=“sudo apt-get install”’ >> ~./bashrc
3)为了安全考虑,忽略别名,强制使用原命令,使用转义符加命令:
\rm

1.8
1)tput工具
tput cols
tput lines
tput longname
tput cup 100 100
tput setb no(no在0~7之间)
tput serf no
tput bold
tput ed
2)stty工具
stty -echo 禁止输出发送到终端。
… stty echo

1.9
1)date的常见使用方法
a. date
Thu May 20 23:09:04 IST 2010
b. date +%s 打印纪元时
1290047248
c. date -d “Jan 20 2001” +%A 获取指定日期星期几
Saturday
2)延时命令
sleep 100 延时100s

1.10
调试脚本,将#!/bin/bash —> #!/bin/bash -xv 即可使用调试功能。

1.11
1)定义函数
a.
function fname()
{
statements;
}

b.
fname()
{
statements;
}

2)执行函数
a.fname;
b.带参数的调用函数
fname arg1 arg2;

3)函数中使用入参
echo $1; #访问第一个参数
echo “$@” 一次性打印所有参数

4)导出函数
export -f fname

5)读取命令或者函数的返回值
echo $?

1.12
1)管道 ” | “,前者的输出作为后者的输入。
ls | cat -n > out.txt
2)读取命令的输出
a.子shell ouput=$(ls | cat -n)
如果需要保留换行和空格,需要使用双引号。 output="$(ls | cat -n)"
b.反引用 output=`ls | cat -n`
3)子shell可以作为一个独立的进程,不干扰主进程
pwd;
(cd /bin; ls;)
pwd;

1.13
1)读取标准输入命令: read
2)可以指定读取的字符个数,而不需要使用额外按回车
read -n 2 var
3)其他用法
read -s var #不回显,常用于密码
read -p “Enter input:” var #显示提示信息
read -t timeout var #设定限时
read -d “:” var #设定定界符,以该符号结束输入。

1.14
1)IFS默认是空格、制表位、换行符
修改IFS,可以通过迭代,自动分割各个元素
data=“name,sex,rollno locatioin”
IFS="," #以逗号作为定界符
for item in $data
do
echo item: $item
done

2)for 循环
for item in list #list可以是string或者是序列,序列的方法:{1…50} {a…z} {A…H}
do
commands
done

3)while循环
while condition
do
commands
done

4)until循环
直到为真,才停止循环
until condition
do
commands
done

1.15
1)条件语句
if condition
then
commands
fi
或者
if condition
then
commands
elif condition
then
commands
else
commands
fi
2)算数比较符号
-eq 等于
-ne 不等于
-gt 大于
-lt 小于
-ge 大于等于
-le 小于等于

3)文件测试
对文件/目录是否可读、可写、是否存在等做判断
4)字符串比较
[[ $str1 == $str2]]
特殊的:
空字符串返回真 [[ -z $str1 ]]
非空返回真: [[ -n $str2 ]]

猜你喜欢

转载自blog.csdn.net/qq_25453065/article/details/85453351
今日推荐