Shell 命令替换

语法格式

方法1: ``
方法2:${command}

示例1:输出用户

#!/bin/bash
#
index=1
for user in `cat /etc/passwd | cut -d ":" -f 1`
do
	echo "This is $index user: $user"
	index=$$(($index + 1))
done 

输出:

This is 1 user: root
This is 2 user: bin
This is 3 user: daemon
This is 4 user: adm
This is 5 user: lp
This is 6 user: sync
This is 7 user: shutdown
This is 8 user: halt
This is 9 user: mail
This is 10 user: operator

示例2:输出系统时间

echo "This is $(date +%Y) year" # This is 2022 year

# 明年
echo "This is $(($(date +%Y) + 1)) year" # This is 2023 year

示例3:已经过了多少星期

date +%j
echo "This year have passed $(date +%j) days"
echo "This year have passed $(($(date +%j)/7)) weeks" # This year have passed 50 weeks
echo "This is $((365-$(date +%j))) days before new year" # This is 11 days before new year

示例4:判断Nginx是否已经启动

wc -l 统计之前命令的结果有几行

#!/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可能不支持。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小叶柏杉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值