There are many kinds of arithmetic operations in the shell, such as a=1,b=2, so how to calculate the value of A+b? Can not simply $a+ $B, if this operation, the result is 1+2, obviously not the result we want, the result is 3, we have a few methods:
1.let C=$A+$B,echo $C 输出的值就为3 2.C=$(( $A+$B )) 3.C=$[$A+$B] 4.C=`expr $A + $B` (需要注意+号与两边的数值之间要有空格隔开,否则C的结果为1+2) 5.。。。
Exercise: Write a script
Given a user, to obtain their password warning period, and then determine whether the remaining age of the user password is less than the warning period, (hint: The calculation method, the maximum period of use minus the number of days that have been used is the remaining period, and then the number of days remaining and the number of warnings) if less than the "Warning"; The "OK" is displayed.
Analysis:
#!/bin/bash user="student" mast_time=`grep "^$user\>" /etc/shadow | cut -d: -f5` #最长时间 now_time=$((`date +%s`/86400)) #现在时间距1970-1-1有多少天 modify_time=`grep "^$user\>" /etc/shadow | cut -d: -f3` #最近一次修改密码时间距1970-1-1过了多少天 use_time=$(($now_time-$modify_time)) #已经使用了的时间 remain_time=$(($mast_time-$use_time)) #剩余时间 warning_time=`grep "^$user\>" /etc/shadow | cut -d: -f6` #警告天数 #打印出这些时间 echo "mast $mast_time" echo "now $now_time" echo "modify $modify_time" echo "use $use_time" echo "remain $remain_time" echo "warning $warning_time" if [[ $remain_time -le $warning_time ]];then echo "warning" else echo "ok" fi
Arithmetic operations in the shell