Search code examples
bashwhile-loopdo-while

Bash: Can I loop commands outside of the If Branch as well?


I am working on a bash script and I'm having some trouble with the while-loop. Below is the section of code that I need help with.

#!/bin/bash
set -e

    # *start*
    read -rp  "  written by: " bit
    tput sgr 0
    cat /home/sir/rmf/posted | egrep -wi --color "${bit,,}" || echo "..."F
    tput setaf 9
    read -rp "  been posted? " repeat
        if [[ $repeat == "no" ]]; then
            tput setaf 2
            echo "let's get this post started."
            post=/home/sir/rmf/active
            cat /home/sir/rmf/header > $post
            tput setaf 13
                 read -rp "  was that they full name? " bit2
                      if [[ $bit2 == "yes" ]]; then
                           author=$bit
                       else
                            read -a author -rp "  well? "
                            author=${author[@]}
                        fi
                        # exit and continue
         elif [[ $repeat == "yes" ]]; then
              echo "alright. "
              # loop back to *start*
         fi

echo "you are now outside the loop."
tput sgr 0
# and continue on to the next part

I've placed the loop in a few different places (wasn't sure if I need to add those to this as well) but either the script exits or I get stuck in it, but I haven't been able to get it to go back to *start*.

Where do I place the while true, do, break, and/or continue so when $repeat == "yes" the code loops back to read -rp "  written by: " bit until $repeat == "no"?


Solution

  • #! /bin/bash
    
    while : ; do
        echo Looping...
        unset repeat
        until [[ $repeat == @(yes|no) ]] ; do
            read -rp 'Repeat?' repeat
        done
        if [[ $repeat == no ]] ; then
            break
        fi
    done
    
    echo Done.