MOHAMED
MOHAMED

Reputation: 43518

Why "read" does not read the first line of a command output?

I want to read the first line of a command output with. but I get an empty message.

I used

ls | read line
echo $line #nothing displayed

Why the line variable is empty and how to fix that?

The following code works. but I want to read only the first line

ls | while read line; do 
    echo $line
done

If it's not possible with read, is it possible to do it with other functions like grep, awk, sed ?

Upvotes: 1

Views: 147

Answers (2)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10643

You can use

read line <<< "$(ls)"
printf "%s\n" "$line"

But as already mentioned, please, PLEASE, PLEASE do not parse ls output!

Upvotes: 2

William Pursell
William Pursell

Reputation: 212158

The read does read the first line, but it is being executed in a subshell. But you can do:

ls | { read line; 
  echo $line;
  # other commands using $line;
}
# After the braces, $line is whatever it was before the braces.

Upvotes: 4

Related Questions