shell编程系列3--命令替换
命令替换
命令替换总结
方法1 `command`
方法2 $(command)
例子1:
获取系统的所有用户并输出
for循环能以空格、换行、tab键作为分隔符
[root@localhost shell]# cat example_1.sh
#!/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
[root@localhost shell]# sh example_1.sh
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
this is 11 user: games
this is 12 user: ftp
this is 13 user: nobody
this is 14 user: systemd-network
this is 15 user: dbus
this is 16 user: polkitd
this is 17 user: sshd
this is 18 user: postfix
this is 19 user: ajie
this is 20 user: chrony
this is 21 user: deploy
例子2:
根据系统时间计算今年或明年
echo "this is $(date +%Y) year"
echo "this is $(( $(date +%Y) + 1)) year"
[root@localhost shell]# echo "This is $(date +%Y) year"
This is 2019 year
[root@localhost shell]# echo "This is $(($(date +%Y) + 1)) year"
This is 2020 year
[root@localhost shell]# echo "$((20+30))"
50
例子3:
根据系统时间获取今年还剩下多少星期,已经过了多少星期
# 今天是今年的第多少天
date +j
# 今年已经过去了多少天
echo "this year have passed $(date +%j) days"
echo "this year have passed $(($(date +%j) / 7)) weeks"
# 今年还剩余多少天
echo "there is $((365 - $(date +%j))) days before new year"
echo "there is $(((365 - $(date +%j)) / 7 )) weeks before new year"
总结:
``和$()两者是等价的,但推荐初学者使用$(),易于掌握;缺点是极少数UNIX可能不支持,但``两者都支持
$(())主要用来进行整数运算,包括加减乘除,引用变量前面可以加$,也可以不加$
$(( (100 + 30) / 13 ))
num1=20;num2=30
((num++));
((num--));
$(( $num1 + $num2 * 2))
语法不是很严格
是否加$都会计算
[root@localhost shell]# num1=50
[root@localhost shell]# num2=70
[root@localhost shell]# echo "$(($num1 + $num2))"
120
[root@localhost shell]# echo "$((num1 + num2))"
120
4.例子4:
判断nginx进程是否存在,如果没有需求拉起这个进程
[root@localhost shell]# cat example_3.sh
#!/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