-命令替换+实战
命令替换就是将一个命令的输出转化为另一个命令的输入。
语法:
使用反引号
`commend`
$(commend)
举几个例子:
列举所有的用户
cat /etc/passwd | cut -d ":" -f 1
#使用awk更简单
#-d 设置 : 为分割符号
#-f 获取第一个field
这样的数据会直接显示到console上,如何将其输出交给下一个命令,比附for循环呢?使用以下脚本
#!/bin/bash
index=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
echo "This is $user-$index"
index=$(($index+1))
done
这样,第一个命令的输出,成为了for循环中的一个输入
根据系统时间计算今年或者明年
echo "next year is $(($(date +%Y) + 1 ))"
注意:其中 date +%Y 是取得date的年份;
这里红色框框里面是将date +%Y 做一个变量替换,黄色的$(())则是算数运算;这里不要混淆。
根据系统时间获取今年还剩下多少星期,已经过了多少个星期: date中有个参数是获取当前天是今年的第几天:
使用这个数字除以7就知道过了多少个星期,用365-这个数字除以7就知道还有多少天了。
echo "This year have passed $(($(date +%j) / 7)) weeks"
echo "There is $(((365 - $(date +%j))/7)) weeks before new year"
其中注意每个括号的作用。
判断nginx进程是否存在,若不存在则自动拉起该进程。
#!/bin/bash
nginx_num=$(ps -ef | grep nginx | grep -v grep | wc -l
)
if [ $nginx_num -eq 0 ] ; then
systemctl start nginx
fi
其中:ps -ef | grep nginx | grep -v grep | wc -l 相关解释:
红色是过滤有nginx 的内容;黄色是对于grep的内容不显示 ;蓝色是统计行数。
作者:句句胖头
https://www.bilibili.com/read/cv6058322
出处: bilibili