The while loop problem in Linux programming

Source: Internet
Author: User
Tags exit sleep linux

To understand the meaning of the while loop, the purpose of using the while loop is to iterate multiple times!

A while loop is a loop that determines whether to exit according to the criteria specified after the while keyword.

If you want to quit with a single command, then you don't need to use a while loop, and using a while means that you want multiple loops, OK, so I guess your question is, how do you exit the loop under the condition that you want true?

If so, there are probably several ways to do so.

1, while the condition is not true forever for true, but to specify a condition, then the condition is not satisfied with the exit.

Examples are as follows:

I=0 while
(i<10) does
echo $i
((i++)
) Sleep 1 done

Tips:

1 The above script executes 10 cycles, that is, 10 seconds later I will not be less than 10, so the loop automatically exits.

2 The above script you can directly command line copy execution to see the effect.

2, you can also use the first part of the shell video special variable $$ to record the script process ID to a fixed file, you want to exit the file to read the script process ID kill this ID can be killed. Examples are as follows:

[Root@c58 ~]# cat w.sh
#!/bin/sh
i=0
echo "$$" >/var/run/shell.pid while
true
does
Echo $i
((i++)) sleep
1
[$i-eq 3] && kill ' cat/var/run/shell.pid '
done
[root@c58 ~]# sh W. SH
0
1
2
terminated

Tip: This setting variable equals 3 kills the script process.

3. Other methods

You can manually find the PID kill Pidno.

Or find the process name Pkill processname

Of course, there are killall commands to use.

In addition, there are problems to ask questions in the answer area.

This article is from the "Old boy Linux operation" blog, please be sure to keep this source http://oldboy.blog.51cto.com/2561410/1294926

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/Linux/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.