Shell脚本--并发执行

本文探讨了Shell脚本中并发执行的概念及其在简化数据库更新操作上的应用,通过实例展示了如何高效地更新数据库统计值,并提供了解决常见警告提示的方法。同时,文章还分享了在使用MySQL进行数据库操作时,如何避免不必要的输出和优化并发执行效率的技巧。

#Shell脚本中并发执行

  1. 顺序执行

#!/bin/bash
echo "Test order execution"
start=$(date +%s)
for ((i=0; i<5; i++))
do
    sleep 2
    echo "Done $i"
done

end=$(date +%s)
take=$((end-start))
echo "Order execution take time(s): $take"

$ bash test_order_exec.sh 
Test order execution
Done 0
Done 1
Done 2
Done 3
Done 4
Order execution take time(s): 10


2. 并发执行

#!/bin/bash

echo "Test concurrent execution"
start=$(date +%s)
for ((i=0; i<5; i++))
do
{
    sleep 2
    echo "Done $i"
} &
done
wait
end=$(date +%s)
take=$((end-start))
echo "Concurrent execution take time(s): $take"

$ bash test_concurrent_exec.sh 
Test concurrent execution
Done 2
Done 0
Done 3
Done 4
Done 1
Concurrent execution take time(s): 2

实际运用:

如果想模拟并发对数据库的更新操作,如更新某一个统计值,如访问次数。可以通过如下的脚本来实现:

#!/bin/bash

for ((i=0; i<100; i++))
do
    mysql -uroot -p123456 -Dtest -e "update count_t set count=count+1;" &
done

补充:

去除恼人的Warning提示

$ mysql -uroot -proot -e "select now()"
Warning: Using a password on the command line interface can be insecure.
+---------------------+
| now()               |
+---------------------+
| 2015-07-05 20:17:05 |
+---------------------+
#清空Warning提示 2代表标准错误输出
$ mysql -uroot -proot -e "select now()" 2>/dev/null
+---------------------+
| now()               |
+---------------------+
| 2015-07-05 20:17:53 |
+---------------------+
#清空所有输出 2等同于1(标准输出)
$ mysql -uroot -proot -e "select now()" >/dev/null 2>&1

参考文档:

http://blog.youkuaiyun.com/wangtaoking1/article/details/9838571


转载于:https://my.oschina.net/zhuguowei/blog/474613

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值