语法格式
方法一
`command`
方法二
$(command)
示例
获取系统所有用户名并输出
index=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "This is $index user:$user"
index=$(($index + 1)) # $后面跟上两个小括号就是算术运算
done
根据系统时间计算今年或明年
echo "This is $(date +%Y) year"
echo "This is $(($(date +%Y) + 1)) year"
根据系统时间获取今年还剩多少星期,已经过了多少星期
date +%j # 一年中的第多少天
echo "This year have passed $(($(date +%j)/7)) weeks"
echo "There is $(((365-$(date +%j))/7)) weeks before new year "
判定nginx进程是否存在,若不存在则自动拉起该进程
#!/bin/bash
nginx_process_num=$(ps -ef|grep nginx | grep -v grep | wc -l)
if [ $nginx_process_num -eq 0 ];then
systemctl start nginx
fi
总结
- ``和() 是等价的,但是推荐初学者使用$(), 易于掌握,缺点是极少数unix可能不支持
- $(())主要用来进行整数运算,包括加减乘除,中间的数值可以加$ 也可以不加$
num1=20;num2=30
((num++))
((num--))
$(($num1+$num2)) 或者 $((num1+num2))