#Shell脚本中并发执行
顺序执行
#!/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.csdn.net/wangtaoking1/article/details/9838571