循环

for

$ cat for_1.sh
#!/bin/sh
for i in 1 2 3 4 5
do
    echo "number ${i}"
done
$ chmod a+x for_1.sh
$ ./for_1.sh
number 1
number 2
number 3
number 4
number 5
$ cat for_2.sh
#!/bin/sh
for i in hello world * 1 2 3
do
    echo "value: ${i}"
done
$ chmod a+x for_2.sh
$ ./for_2.sh
value: hello
value: world
value: Desktop
value: Documents
value: Downloads
value: Music
value: Pictures
value: Public
value: Templates
value: Videos
value: examples.desktop
value: for_2.sh
value: go
value: snap
value: 1
value: 2
value: 3

while

$ cat while_1.sh
#!/bin/sh
INPUT_STRING=""
while [ "${INPUT_STRING}" != "bye" ]
do
    echo "type some string in (bye to quit)."
    read INPUT_STRING
    echo "echo ${INPUT_STRING}"
done
$ chmod a+x while_1.sh
$ ./while_1.sh
type some string in (bye to quit).
ls
echo ls
type some string in (bye to quit).
bye
echo bye

:代表true,下面是无限循环;break可以跳出循环。

$ cat while_2.sh
#!/bin/sh
INPUT_STRING=""
while :
do
    echo "type some string in (Ctrl+C to quit)"
    read INPUT_STRING
    echo "echo ${INPUT_STRING}"
done
$ chmod a+x while_2.sh
$ ./while_2.sh
type some string in (Ctrl+C to quit)
ls
echo ls
type some string in (Ctrl+C to quit)
^C
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容