Reputation: 133
I am trying to figure out a way to display the longest line entered from user inputs.
For example, my script so far will have the user input in 4 lines:
Hello
Hello will
Hello will turner
Hello will turner honey
In my code I have:
echo "Please enter 4 lines:"
read LINE1
read LINE2
read LINE3
read LINE4
I am wondering if there is a way for me to count each of my lines and then output the biggest one. Making a file would probably be easiest but I wanted to know if I could just use the Bash commands to do so.
Upvotes: 1
Views: 126
Reputation: 84403
You don't explain what you expect to happen when two or more lines are the same length. I therefore make the assumption that when two lines are the same length, one should store and report the newer line as "longest."
A more idiomatic (and in my opinion clearer) way of doing this with Bash 4.x would be:
#!/usr/bin/env bash
# Guard against exported environment variables.
unset longest_line
for line in {1..4}; do
read -p "Enter line $line: "
(( "${#REPLY}" >= "${#longest_line}" )) && longest_line="$REPLY"
done
echo "$longest_line"
This uses a variety of shell expansions, the read builtin's -p
flag to prompt, read's default REPLY variable to hold the result, and a line-length comparison against the longest line seen so far to perform the key task.
In this example, you don't even have to initialize a value for longest_line since the length of an unset variable is zero, but it's a good defensive programming practice not to rely on the variable being unset. If you prefer to actually set the initial state of the variable yourself, you can set it to the empty string instead with longest_line=''
.
The code above will generate the expected result:
$ bash longest_line.sh Enter line 1: foo Enter line 2: bar Enter line 3: foo bar Enter line 4: baz foo bar
Upvotes: 1
Reputation: 121407
If you are only interested in the longest line then you can use a loop and compare the current line with the next line you read:
#!/bin/bash
max=0
for((i=0;i<4;i++)); do
read -r line
len=${#line}
if [[ len -gt max ]] ; then
max=$len
long="${line}"
fi
done
echo longest line="${long}" length="${max}"
If you want to keep the other lines, then you can use an array and apply the same logic on the array.
Upvotes: 1