Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a list of filenames in a file and want to do let the user decide what to do with each. In bash, iterating over filenames is not trivial in itself, so I followed this answer:

#!/bin/bash

while IFS= read -r THELINE; 
do
  read -n 1 -p "Print line? [y/n] " answer;
  if [ ${answer} = "y" ];
  then
    echo "${THELINE}";
  fi;
done < tester;

When I try to execute this (on a non-empty file), I get an error at the if:

line 5: [: =: unary operator expected

My best guess is that answer is not set properly, which would be caused by using two calls of read in a "nested" fashion since the following works as expected:

#!/bin/bash

for THELINE in $(cat "tester");
do
  read -n 1 -p "Print line? [y/n] " answer;
  if [ ${answer} = "y" ];
  then
    echo "${THELINE}";
  fi;
done;

What is going on here?

I run bash 4.2.24(1)-release (x86_64-pc-linux-gnu) on 3.2.0-37-generic #58-Ubuntu x86_64 GNU/Linux.

share|improve this question
1  
try replacing the ${answer} = "y" with "${answer}" == "y" –  mauro.stettler Feb 24 '13 at 16:10
    
@mauro.stettler: That gets rid of the error. Now the script does iterate, but never prompts. –  Raphael Feb 24 '13 at 16:29
    
I'm not sure what the scope of the IFS= in your first while is, that might mess up things. –  vonbrand Feb 24 '13 at 19:04
    
@vonbrand The scope is the read command. –  Gilles Feb 24 '13 at 22:43
add comment

2 Answers

up vote 3 down vote accepted

First, the error from [ is because answer is empty, so [ sees three arguments: =, y and ]. Always put double quotes around variable substitutions: if [ "$answer" = "y" ].

The reason $answer is empty fd 0 is busy with the file input due to the redirection <tester over the while loop.

while IFS= read -r line <&3
do
    read -n 1 -p "Print line? [y/n] " answer
    if test "$answer" = "y"
    then
        echo "$line"
    fi
done 3< tester
share|improve this answer
    
You mean fd0 (/dev/stdin)? –  Hauke Laging Feb 24 '13 at 17:14
add comment

Try if [ x${answer} = "xy" ];. test does need something before =

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.