Ending while loop using if - bash

Is there a way to end a while loop by using an if? Here's just some pseudocode of the basics of what I want to do:
re = 1
while [re = 1]
do
echo "hello, enter name"
read name
echo name
echo "continue? 1 for yes, 0 for no"
read re
if [re == 1]
then
pass
elif [re == 0]
then
end while
else
pass

It looks like you need to use continue in place of pass if you want to skip the rest of the loop and start again from the beginning, and you need to use break instead of end while if you want to exit the loop altogether.

Yes, bash supports the break command to do that:
 i=0;
while [ $i -lt 10 ]; do
if [ $i -eq 3 ]; then
break
fi
echo $i
let i++
done
Will output:
0
1
2

Related

Loop BASH with counter in one line

I wait program finish and print nothing; but this intro in loop:
while [ 0 > 0 ]; do echo 1; done
logically 0 no't is > to 0...
why get loop?
How I can get nothing by screen? and program finish fine?
After of my progam "nothing to do":
while [ 0 > 0 ]; do echo 1; done
I like in one line:
q = 0; while [ q < 9 ]; q ++; do echo q; done
it´s possible in one line?
Thanks
q = 0; while [ q < 9 ]; q ++; do echo q; done
Just 5 errors in one line.
q=0 may not have white space around the assignment operator
q ++ has to be in double round parens
q < 9 has to be -lt (less than)
in single brackets [ $q -lt 9 ] q needs to be $q
the do should follow the while
Possible solution:
q=0; while [[ q -lt 3 ]]; do ((q++)); echo $q; done
1
2
3
echoing values can be done with
echo {1..9}
too, but is not flexible, so you can't use variable expansion inside, like echo {1..$n}. The canonical way of doing initialization, increment and threshold check, is a for loop:
for (( q=1; q < 4; ++q)); do echo $q ; done
There is the external program seq, which is not so much recommended, for that reason:
seq 1 3
First question:
while [ 0 > 0 ]; do echo 1; done
Look for a file 0 where you used file redirection (instead of -gt), like in echo foo > 0.file.
Instead of
while [ 0 -gt 0 ]; do echo 1; done
because it does nothing. It doesn't wait for anything. Either your program is sequential, then it is finished at that point anyhow. Or there is a program/command in the background running, which doesn't care about this anti loop anyhow.
For your second question, use
for (( expr1 ; expr2 ; expr3 )) ; do list ; done
Also refer to man bash

Is it possible to break a for loop in bash?

I have the below scenario.
I'm iterating through array elements in bash and comparing the values.
#!/bin/bash
for (( i = 0 ; i <=m-1 ; i++));
do for (( j = 0 ; j <=n-1 ; j++));
do
if [ "${sourcedisktype[i]}" == "SSD" -a "${targetdisktype[j]}" == "BSAS" ];
then echo "volume cannot be moved1";
elif [ "${sourcedisktype[i]}" == "SSD" -a "${targetdisktype[j]}" == "SAS" ];
then echo "volume cannot be moved2";
elif [ "${sourcedisktype[i]}" == "SAS" -a "${targetdisktype[j]}" == "BSAS" ];
then echo "volume cannot be moved3";else
echo "Volume can be moved for this combination of disk type";done;done;
I don't want to execute the else part even if one elif fails. Is there any way to do it. Is it possible to use break statement after elif?
Of course you can break out of your loops in bash, you can actually even break out of N nested loops if you use the statement break N where N is an integer >=1.
For more details please have a look at the documentation:
http://tldp.org/LDP/abs/html/loopcontrol.html
You can actually also use continue N but it can be quite tricky and hard for others to understand, so I would not recommend to use it.
PS: do not forget to indent your code properly in order for others to understand it quickly and even for yourself, I can affirm that it will be a pain if you try to reread your code in a couple of months/years. You will regret not having indented/commented it properly.

Bash Script accepting a number, then printing a set of int from 0 to the number entered

I am trying to write a bash script that accepts a number from the keyboard, and then prints a set of integers from 0 to the number entered. I can't figure out how to do it at all.
This is my code:
while [ 1 ]
do
echo -n "Enter a color: "
read user_answer
for (( $user_answer = $user_answer; $user_answer>0; $user_answer--))
echo $user_answer
fi
done
exit
The error I'm recieving is:
number_loop: line 10: syntax error near unexpected token echo'
number_loop: line 10: echo $user_answer'
Assign a separate variable in order to use increment/decrement operators. $user_answer=$user_answer will always be true and it will throw an error when trying to use decrement. Try the following :
#!/bin/bash
while [ 1 ]
do
echo -n "Enter a color: "
read user_answer
for (( i=$user_answer; i>0; i-- ))
do
echo $i
done
done
exit
You missed the do statement between your for and the echo.
bash has many options to write numbers. What you seem to be trying to do is easiest done with seq:
seq $user_answer -1 0
If you want to use your loop, you have to insert a ; do and replace the fi with done, and replace several $user_answer:
for (( i = $user_answer; i>0; i--)); do
echo $i
done
(btw: I assumed that you wanted to write the numbers in reverse order, as you are going backwards in your loop. Forwards is even easier with seq:
seq 0 $user_input
)
This is where a c-style loop works particularly well:
#!/bin/bash
for ((i = 1; i <= $1; i++)); do
printf "%s\n" "$i"
done
exit 0
Example
$ bash simplefor.sh 10
1
2
3
4
5
6
7
8
9
10
Note: <= is used as the for loop test so it 10 it iterates 1-10 instead of 0-9.
In your particular case, iterating from $user_answer you would want:
for (( i = $user_answer; i > 0; i--)); do
echo $i
done
The for loop is a bash internal command, so it doesn't fork a new process.
The seq command has a nice, one-line syntax.
To get the best of the twos, you can use the { .. } syntax:
eval echo {1..$answer}

Shell script for word in $sentece How to change the value of word?

I need some help from this awesome community.
I'm trying to write a script that loops through each word of a sentence stored in a variable (for example SENTENCE).
Example:
for WORD in $SENTENCE
do
echo do something
done
The problem that I'm facing is that I need to change the value of WORD to restart the loop if a certain condition is true inside the loop.
Example:
for WORD in $SENTENCE
do
echo do something
if [[ $SOMETHING_HAPPENED == TRUE ]]; then
WORD=$FIRST_WORD_IN_SENTENCE
fi
done
Basically, I need to restart the loop if certain conditions are met (SOMETHING_HAPPENED), but I don't know how to do this properly.
If this was a normal C loop I would do it like this:
for (i=0;i<10;i++){
do_something();
if (SOMETHING_HAPPENED == TRUE){
i=0;
}
}
How do I do this in shell script?
Thank you.
You could use a loop around your for loop that executes the for loop until the something doesn't happen:
repeat=yes
while [ "$repeat" = yes ]; do
repeat=no
for WORD in $SENTENCE; do
# do something
if [[ $SOMETHING_HAPPENED == TRUE ]]; then
repeat=yes
break
fi
done
done
while [[ 1 ]]; do # infinite loop
for word in $sentence; do
…
if [[ $condition ]]; then
continue 2 # go to the next iteration of the *outer* loop
fi
done
break # escape the outer loop
done
To restart the loop you can use BASH arrays and run your loop like this:
arr=( $sentence )
for ((i=0; i<${#arr[#]}; i++)); do
word="${arr[$i]}"
# evaluate condition
if [[ "$SOMETHING_HAPPENED" == TRUE ]]; then
i=0
continue
fi
echo "$word"
done

Loop first run continue in shell script

How to break out of infinite while loop in a shell script?
I want to implement the following PHP code in shell script(s):
$i=1;
while( 1 ) {
if ( $i == 1 ) continue;
if ( $i > 9 ) break;
$i++;
}
break works in shell scripts as well, but it's better to check the condition in the while clause than inside the loop, as Zsolt suggested. Assuming you've got some more complicated logic in the loop before checking the condition (that is, what you really want is a do..while loop) you can do the following:
i=1
while true
do
if [ "$i" -eq 1 ]
then
continue
fi
# Other stuff which might even modify $i
if [ $i -gt 9 ]
then
let i+=1
break
fi
done
If you really just want to repeat something $count times, there's a much easier way:
for index in $(seq 1 $count)
do
# Stuff
done
i=1
while [ $i -gt 9 ] ; do
# do something here
i=$(($i+1))
done
Is one of the ways you can do it.
HTH

Resources