Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Shell scripts break and continue commands

Shulou Source: shulou.com Published: 2022-06-03 08:22:20 09月29日 Update

This article introduces the knowledge of "how to use Shell scripts break and continue commands". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

During a loop, it is sometimes necessary to force a jump out of the loop when the end condition of the loop is not reached, and Shell uses two commands to do this: break and continue.

Break command

The break command allows you to jump out of all loops (terminating execution of all subsequent loops).

In the following example, the script enters an endless loop until the user enters a number greater than 5. To jump out of this loop and return to the shell prompt, you need to use the break command.

The code is as follows:

#! / bin/bash

While:

Do

Echo-n "Input a number between 1 to 5:"

Read aNum

Case $aNum in

1 | 2 | 3 | 4 | 5) echo "Your number is $aNum!"

*) echo "You do not select a number between 1 to 5, game is over!"

Break

Esac

Done

Continue

The continue command is similar to the break command, except that it does not jump out of all loops, just out of the current loop.

Modify the above example:

The code is as follows:

#! / bin/bash

While:

Do

Echo-n "Input a number between 1 to 5:"

Read aNum

Case $aNum in

1 | 2 | 3 | 4 | 5) echo "Your number is $aNum!"

*) echo "You do not select a number between 1 to 5!"

Continue

Echo "Game is over!"

Esac

Done

The running code finds that when you enter a number greater than 5, the loop in this example does not end, the statement

The code is as follows:

Echo "Game is over!"

Will never be executed.

That's all for "how to use Shell scripts break and continue commands". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Loops commands code scripts examples content numbers more knowledge process face-to-face input utility learning and then two functions only dilemmas reality. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Docker OPPO Reno Xiaomi MySQL