| 1 | 方法一 | 方法二 |
|---|---|---|
| 语法格式 | `command` | $(command) |
例子
例子1:
获取系统得所有用户并输出1
2
3
4
5
6[root@master datas]# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
# cut 切分 -d 指定分隔符 -f 取段
[root@master datas]# cat /etc/passwd | cut -d ":" -f 1
root1
2
3
4
5
6
7
8
9#!/bin/sh
ind=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "This is $ind user: $user"
ind=$(($ind + 1))
done例子2:
根据系统时间计算今年或明年1
2
3
4
5
6
7
8
9[root@master datas]# date
Sat Dec 7 00:01:44 CST 2019
[root@master datas]# date +%Y
2019
[root@master datas]# echo "This is $(date +%Y) year"
This is 2019 year
[root@master datas]# echo "This is $(($(date +%Y) + 1)) year"
This is 2020 year
- 例子3:
根据系统时间获取今年还剩下多少星期,已经过了多少星期1
2
3
4
5[root@slave2 datasets]# echo "This yaer have passed $(date +%j) days"
This yaer have passed 341 days
[root@slave2 datasets]# echo "This yaer have passed $(($(date +%j)/7)) weeks"
This yaer have passed 48 weeks
- 例子4:
判定nginx进程是否存在,若不存在则自动拉起该进程
说明:
-v grep 去掉grep本身进程
wc -l 统计结果行数
V
1 | ps -ef | grep nginx -v grep |wc -l |
1 | #!/bin/bash |
总结: ``和$()两者是等价的,但推荐初学者使用$(),易于掌握;缺点是极少数UNIX可能不支持
$(())主要用来进行整数运算,包括加减乘除,引用变量前面可以加$,也可以不加$