While loop in Bash script?
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?
whi开发者_Python百科le read myline
do
echo ${myline}
done
echo "Hello"
while read line
do
true
done
exit 0
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
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
This is a way to emulate a do
while
loop in Bash, It always executes once and does the test at the end.
while
read -r line
[[ $line ]]
do
:
done
When an empty line is entered, the loop exits. The variable will be empty at that point, but you could set another variable to its value to preserve it, if needed.
while
save=$line
read -r line
[[ $line ]]
do
:
done
What are you trying to do? From the look of it it seems that you are trying to read into a variable?
This is done by simply stating read the value can then be found inside of $
ex:
read myvar
echo $myvar
As other have stated the trouble with the loop is that it is empty which is not allowed.
If you are looking to create a menu with choices as a infinite loop (with the choice to break out)
PS3='Please enter your choice: '
options=("hello" "date" "quit")
select opt in "${options[@]}"
do
case $opt in
"hello") echo "world";;
"date") echo $(date);;
"quit")
break;;
*) echo "invalid option";;
esac
done
PS3 is described here
If you type help while
in bash you'll get an explanation of the command.
精彩评论