From 4a7606507d4e5ace68b42630333ff7b8bde7e44c Mon Sep 17 00:00:00 2001 From: waldek Date: Thu, 14 Jul 2022 15:49:06 +0200 Subject: [PATCH] quick break and continue example --- advanced/learning_bash_scripting.md | 83 +++++++++++++++++++++++------ 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/advanced/learning_bash_scripting.md b/advanced/learning_bash_scripting.md index b8b7395..e10dac3 100644 --- a/advanced/learning_bash_scripting.md +++ b/advanced/learning_bash_scripting.md @@ -1139,7 +1139,74 @@ waldek@debian:~$ ## `break` and `continue` -TODO +When we consider the `secret.sh` password checker we made, we have a problem. +The program always exits, either with a success code `0` or with an error of `1`. +In order to *break* a loop conditionally we need a new keyword, `break`. +I rewrote the same script but with a more logical flow of operation. + +```bash +#!/bin/bash + +secret="test123" +tries=3 + +while true; do + read -s -p "your password please: " password + if [[ $password == $secret ]]; then + echo "access granted!" + break + else + (( tries-- )) + if [[ $tries -eq 0 ]]; then + echo "access denied!" + exit 1 + fi + echo "wrong password, you have $tries left..." + fi +done + +echo "we're in!" +echo "the code keeps on flowing..." +``` + +`continue` is very similar to `break`. +It *breaks* the current iteration and **continues** to the next cycle. +Consider the example below. + +```bash +#!/bin/bash + +counter=0 +value=0 + +while [[ $counter -lt 100 ]]; do + if (( $counter % 2 )); then + echo "$counter is even" + random=$(( $RANDOM % 20 )) + echo "adding $random to the counter" + counter=$(( $random + $counter )) + echo "and I'll loop again" + continue + fi + echo "incrementing $counter by just one..." + (( counter++ )) +done +``` + +# Functions - Reuse code to make life easier. + +## defining a function + +## function arguments + +## global vs local variable + +## return values + +## the `command` builtin + +[Ryan's tutorials](https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php) + # Coding challenge - pipe or argument plus action! @@ -1247,20 +1314,6 @@ done -# Functions - Reuse code to make life easier. - -## defining a function - -## function arguments - -## global vs local variable - -## return values - -## the `command` builtin - -[Ryan's tutorials](https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php) - # Coding challenge - Student reports With the [following](../assets/scores.csv) file write me a program that prints: