运算
let
操作
- 可以直接执行基本的算术操作;使用时,变量名之前不需要再添加
$;
#!/bin/bash
no1=4;
no2=5;
let result=no1+no2
echo $result
- 自增自减操作:
let no1++ / ++no1;
let no1-- / --no1;
//
let no+=6
let no-=6
[]
操作
- 使用方法和
let
命令类似;
#!/bin/bash
no1=4;
no2=5;
result=$[no1+no2]
echo $result
- 在
[]
中也可以使用$
前缀;效果与不使用相同; - 也可以使用
(())
,但使用(())
时,变量名之前需要加上$
;
result=$(( no1 + 50 ))
使用expr
操作
result=`expr 3 + 4`
result=$(expr $no1 + 5)
注意,以上这些方法只能用于整数运算,而不支持浮点数;
使用bc
- 一个用于数学运算的高级工具,可以借助它执行浮点数运算并应用一些高级函数;
- 可能需要安装:
apt-get install bc
echo "4 * 0.56" | bc
2.24
//
no=54;
result=`echo "$no * 1.5" | bc`
echo $result
81.0
- 设定小数精度
echo "scale=2;3/8" | bc
0.37
- 进制转换
#!/bin/bash
#十进制转二进展然后二进行转十进制;
no=100
echo "obase=2;$no" | bc
1100100
no=1100100
echo "obase=10;ibase=2;$no" | bc
100
- 计算平方以及平方根
echo "sqrt(100)" | bc #Square root
echo "10^10" | bc #Square
数组和关联数组
定义一般数组
#这些值将会存储在以0为起始索引的连续位置上
array_var=(1 2 3 4 5 6)
#将数组定义成一组“索引-值”:
array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"
定义关联数组
- 可以用任意的文本作为数组索引;
//声明
declare -A ass_array
//添加
ass_array=([index1]=val1 [index2]=val2)
ass_array[index1]=val1
ass_array[index2]=val2
打印数组
- 打印值
echo ${array_var[0]}
//
index=5
echo ${array_var[$index]}
//打印所有值
echo ${array_var[*]}
echo ${array_var[@]}
- 打印长度
echo ${#array_var[*]}
echo ${#array_var[@]}
- 打印索引
echo ${!array_var[*]}
echo ${!fruits_value[*]}
cat进行拼接
常用作用
- 用于读取、显示或拼接文件内容
cat file1 file2 file3 ...
//使用管道操作符: OUTPUT_FROM_SOME COMMANDS | cat
echo 'Text through stdin' | cat - file1 file2..
- 输出时增加行号:
//保留空白输出输出
cat -n file
//过滤空白行输出
cat -b file
- 过滤多余空白行:
cat -s file;
- 将制表符显示为
^|
- 制表符(TAB)的功能是在不使用表格的情况下在垂直方向按列对齐文本;
- 对于缩进有要求的语言若在应该使用空格的地方误用了制表符的话,就会产生缩进错误;
- 该特性对排除缩进错误非常有用;
文件描述符及重定向
文件描述符
- 与文件输入、输出相关联的整数;用来跟踪已打开的文件;
stdin: 0,stdout: 1,stderr: 2`
处理输出文本
> = 1>; >> = 1>>
//将输出文本重定向或保存到一个文件中
echo "This is a sample text 1" > temp.txt
//将文本追加到目标文件中
echo "This is sample text 2" >> temp.txt
输出结果重定向
echo $?;
可以打印退出的状态;
ls 1> out.txt
ls + 2> out.txt
-
链式:
cmd 2>stderr.txt 1>stdout.txt
-
重定向到同一个文件
//将stderr转换成stdout,使得stderr和stdout都被重定向到同一个文件中:
cmd 2>&1 output.txt
cmd &> output.txt
过滤输出的stderr
信息;
- 处理错误时,可以将
stderr
的输出重定向到/dev/null
;它是一个特殊的设备文件,接收到的任何数据都会被丢弃;
使用tee
:
- 既可以将数据重定向到文件,还可以提供一份重定向数据的副本作为后续命令的
stdin
cat a* | tee out.txt | cat -n
- 追加
cat a* | tee -a out.txt | cat -n
使用stdin
作为命令参数
//只需要将-作为命令的文件名参数即可
cmd1 | cmd2 | cmd -