Reputation: 186
This program is intended to read a file from stdin and return the longest and shortest lines. Right now it's in an infinite loop.Could someone tell me what I'm doing wrong?
Update: So after reading more about what read does, it's actually right (yay me) but I want to set the delimiter to a newline character while currently the read command is taking a string at every whitespace character. Does anyone know what I can do?
read T
short=""
long=""
for i in $T; do
if [[ $short = "" ]]; then
short=$i
elif [[ ${#i} -lt ${#short} ]]; then
short=$i
elif [[ ${#i} -gt ${#long} ]];then
long=$i
fi
done
echo $short
echo $long
Upvotes: 0
Views: 255
Reputation: 876
It can't possibly reach an infinite loop, since you are looping over a
necessarily finite variable ($T
).
I'm going to assume that your script is "hanging" and assume one of the possible reasons (to provide you one possible solution to your classroom problem): that the script is sleeping waiting for data from stdin and no data is being sent to him.
Here's what you could do:
read short
long=$short
while read line; do
if [[ ${#line} -lt ${#short} ]]; then
short=$line
fi
if [[ ${#line} -gt ${#long} ]]; then
long=$line
fi
done
echo $short
echo $long
Notice that I've first initialized the short
and long
with the
first line of input, or empty string on stdin's EOF. Then I attempt
to read more lines in a while loop to then check for conditions to update short
and
long
; it is important to not exclude the line size checks if one
of them applies (like you didn't in your script using elif
s).
Upvotes: 1