Register
It is currently Mon Oct 20, 2014 11:52 am

read from keyboard into read from file loop


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Fri May 18, 2012 2:40 pm   

Joined: Fri May 18, 2012 2:31 pm
Posts: 1
I need you help, please

I have a scipt like this


1 cat myfile |while read line
2 echo $line
3 echo "It's the correct line?"
4 read yourinput
5 if [ "$yourinput" = "y" ]; then
6 echo "Found!"
7 fi
8 done

The problem is the line 4. The script read them from the file and not from the keyboard
Any solutions?
Thanks in advance


Top
 Profile  
 PostPosted: Fri May 18, 2012 2:58 pm   
Moderator
User avatar

Joined: Wed May 03, 2006 2:05 pm
Posts: 242
Hello cefer!

I think what you're looking for is 'read -p' (to prompt the user for input).
You should check out the 'man' page for the 'read' command:

Code:
  -p prompt
    Display prompt, without a trailing newline, before attempting
    to read any input. The prompt is displayed only if input is coming from a
    terminal.


Top
 Profile YIM  
 PostPosted: Fri May 18, 2012 4:01 pm   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
You're right. read(0) is reading from the file, or more precisely from the file descriptor 0 which is redirected to the file called myfile.
So you have to specify that you want to read the user's input from the standard input, which is the file descriptor 0. ( « help '\read' » )

I've done an improved version... redirecting FD 3 to the file to avoid redirecting FD 0.
In this case, it's better, because you don't know whether the file contains many lines.

Code:
#!/bin/bash

if (($# != 1)); then
    printf 'usage: ./%s filename\n' "${0##*/}" >&2
    exit 1
elif [[ ! -f $1 ]]; then
    printf '« %s »: no such file found.\n' "$1" >&2
    exit 1
fi

exec 3< "$1"
shopt -s extglob nocasematch

echo $'Is it the correct line?\n'

_line_found=0
while ((! _line_found)) && IFS= read -r -u 3; do
    if [[ ! ${REPLY//[[:space:]]} ]]; then
        continue
    fi 
   
    if ! read -er -i nope -p "« $REPLY » ? " \
              -t 10 ans; then
        echo
    fi 

    if [[ $ans = @(q|quit|exit) ]]; then
        exit
    elif [[ $ans = y || $ans = ye[sp] ]]; then
        echo $'\nLine found!'
        _line_found=1
    fi 
done

exec 3>&-


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: uhelp and 6 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP