循环
2019-01-12 本文已影响2人
时海观察者
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