Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop in Bash script?

Tags:

linux

bash

I'm not used to writing Bash scripts, and Google didn't help in figuring out what is wrong with this script:

#!/bin/bash
while read myline
do
done

echo "Hello"
while read line
do
done

exit 0

The output I get is:

./basic.agi: line 4: syntax error near unexpected token 'done'
./basic.agi: line 4: 'done'

and my bash version is:

GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)

Thank you.


Edit: The script works OK when the while loop isn't empty.

While I'm at it... I expected to exit the loop when the user typed nothing, ie. simply hit the Enter key, but Bash keeps looping. How can I exit the loop?

while read myline
do
        echo ${myline}
done

echo "Hello"
while read line
do
        true
done

exit 0
like image 952
Gulbahar Avatar asked Feb 24 '11 12:02

Gulbahar


2 Answers

You can't have an empty loop. If you want a placeholder, just use true.

#!/bin/bash
while read myline
do
    true
done

or, more likely, do something useful with the input:

#!/bin/bash
while read myline
do
    echo "You entered [$line]"
done

As for your second question, on how to exit the loop when the user just presses ENTER with nothing else, you can do something:

#!/bin/bash
read line
while [[ "$line" != "" ]] ; do
    echo "You entered [$line]"
    read line
done
like image 163
paxdiablo Avatar answered Oct 14 '22 02:10

paxdiablo


When you are using the read command in a while loop it need input:

echo "Hello" | while read line ; do echo $line ; done

or using several lines:

echo "Hello" | while read line
    do
    echo $line
done
like image 29
Anders Zommarin Avatar answered Oct 14 '22 01:10

Anders Zommarin