Nat! bio photo

Nat!

Senior Mull.

Twitter RSS

Github

Test your shell scripting prowess

Can you tell the output of this shell script without running it ?

#!/bin/sh

echo "VfL Bochum 1848" | while read x 
do
    echo "$x" 
    rc=$?
done

if [ $rc -ne 0 ]
then
   echo "echo reported an error"
fi

4 Comments

A photo of dwt

From: dwt

Uhm

This? "test.sh: line 9: [: -ne: unary operator expected"

cu Martin

A photo of Nat!

From: Nat!

Actually to be pedantic it's

VfL Bochum 1848

test.sh: line 9: [: -ne: unary operator expected

As your anwer is byte perfect,I have the suspicion that you did cheat a little, so do you know why it is saying that ?

That problem had me stumped in a real life script for quite some time.

A photo of Nicola

From: Nicola

The '|' causes both sides to be executed in a subshell. So the 'while' loop is executed in a subshell. That means that the 'rc' variable set in the 'while' loop is set in a subshell, and is lost when you get out of it.

When you later check the value of 'rc', it's an empty variable (undefined in the parent shell) so you'll get an error.

A photo of Nat!

From: Nat!

Excellent. We have a winner!

Post a comment

All comments are held for moderation; basic HTML formatting accepted.

Name:
E-mail: (not published)
Website: