目录
1.Doing math calculations with the shell
2.Playing with file descriptors and redirection
1.Doing math calculations with the shell
Bash shell 使用 let,(( )) 、 [] 、expr、进行基础的数学运算。 bc 执行浮点数计算。
(1)let :
let : 用于执行基础操作,当使用let时,可以不使用 "$"
let result=no1+no2
echo $result
#加法操作
let no1++
#减法操作
let no1--
#shorthands
let no+=6 : let no=no+6
let no-=6 : let no=no-6
(2)[] && (( )):
result=$[ no1 + no2 ]
result=$[ $no1 + 5 ]
result=$(( no1 + 50 ))
(3)expr :
result=`expr 3 + 4`
result=$(expr $no1 + 5)
注意: 上面四种操作只支持整形变量,不支持浮点数。 如果想要计算浮点数,需要使用精度计算器 bc
echo "4 * 0.56" | bc
2.24
BC 的几种附加操作:
- 十进制精度: 例如 scale=2 时,
echo "scale=2;3/8" | bc
0.37
- Base conversion with bc: 进制转换
#!bin/bash
Description: Number conversion
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
2.Playing with file descriptors and redirection
stdin 、stdout 、stderr
在编写脚本时,经常使用 stdin,stdout,stderr。 通过过滤内容将输出重定向到文件是我们需要执行的基本操作之一。
- 0 stdin
- 1 stdout
- 2 stderr
(1)用法:
重定向 和 保存输出文本:
$ echo "This is a sample text l" > temp.txt
使用这个命令,文件之前的内容会被清除
$echo "This is sample text 2" >> temp.txt
这将把输出追加到文件中。
cat 观察文本内容
$ cat temp.txt
This is sample text 1
This is sample text 2
(2)标准错误输出的例子:
$ ls +
ls: cannot access +: No such file or directory
Here + is an invalid argument and hence an error is returned
脚本通过在程序结束后立即执行 $?判断程序是否执行成功,成功返回0,不成功返回1.
#存在test文件夹的情况,输出被重定向到out.txt文件中。
ls test/ >out.txt
ls + 2> err.txt #书上说可以将stderr重定向到err.txt文件,但是没有成功。
3.数组和关联数组
Bash 支持常规数组和关联数组。
常规数组: 只使用整形(int)作参数。
关联数组: 可以使用字符串(string)作为参数。(Bash 4.0及以上支持)
array_var=(1 2 3 4 5 6)
#Values will be stored in consecutive locations starting from index 0.
array_var[0]="test1"
array_var[1]="test2"
#Print:
echo ${array_var[0]}
test1
index=1
echo ${array_var[$index]}
test2
#Print all the values
echo ${array_var[*]}
#Print the length of an array
echo ${#array_var[*]}
6
打印字符串长度时也使用了#
关联数组:
#!/bin/sh
#this program is used to capture info from test log
#################################
log_name=$1
loop_num=$2
output_file="out_put_log.txt"
loop_indx=0
declare -a t1
declare -a t2
declare -a t3
declare -a t4
t1[$loop_indx]=`grep "t1_vec" $log_name | awk '{printf("%g", $8)}'`
数组声明:
declare -A ass_array
添加元素:
ass_array=([index1]=vall [index2]=val2)
ass_array[index1]=val1
ass_array[index2]=val2
For example:
$ declare -A fruits_value
$ fruits_value=([apple]='100dollars' [orange]='150 dollars')
$ echo "Apple costs ${fruits_value[apple]}"
Apple costs 100 dollars