脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - shell - Linux命令行循环执行shell命令

Linux命令行循环执行shell命令

2023-03-07 12:11导数题 shell

这篇文章主要介绍了Linux命令行,循环执行shell命令的相关知识,主要包括死循环,普通计数循环,以及Linux shell循环命令 while死循环的用法,需要的朋友可以参考下

Linux命令行,循环执行shell命令

死循环

命令格式

?
1
while true ;do <command>; done;

可以将 command 替换为任意命令。
下面以echo “hello”; sleep 1;为 command 展示最终效果

效果

?
1
2
3
4
5
6
7
8
wanghan@ubuntu:~$ while true ;do echo "hello"; sleep 1; done;
hello
hello
hello
hello
hello
^C
wanghan@ubuntu:~$

每隔一秒,打印一次hello,直到按下Ctrl+C才停止。

普通计数循环

循环10次

?
1
mycount=0; while (( $mycount < 10 )); do  <command>;((mycount=$mycount+1)); done;

可以将 command 替换为任意命令。
下面以 echo “mycount=$mycount”;为 command 展示最终效果

效果

?
1
2
3
4
5
6
7
8
9
10
11
wanghan@ubuntu:~$ mycount=0; while (( $mycount < 10 )); do echo "mycount=$mycount"; ((mycount=$mycount+1)); done;
mycount=0
mycount=1
mycount=2
mycount=3
mycount=4
mycount=5
mycount=6
mycount=7
mycount=8
mycount=9

mycount计数到10后停止循环。

以上内容到此介绍,下面介绍下Linux shell循环命令。

Linux shell循环命令 while死循环的用法

作为硬件工程师,偶尔会用到Linux shell编程,这里只将while死循环,有相关需求的工程师可以参考。

死循环也就是无限循环,它由 while true (表示条件始终为真)或 while : (表示空表达式)组成,其中冒号(:)等效于无操作,冒号和while之间有空格。实例代码如下:

?
1
2
3
4
5
#!/bin/bash
while true  #same to while :
do
echo "drink more water!!"
done

运行结果如下:

root@nihao:~# ./nihaoaaaa.sh
drink more water!!
drink more water!!
drink more water!!
drink more water!!
drink more water!!
drink more water!!
drink more water!!
drink more water!!
...

到此这篇关于Linux命令行,循环执行shell命令的文章就介绍到这了,更多相关linux shell循环执行命令内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/daoshuti/article/details/72831256

延伸 · 阅读

精彩推荐