Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have the following script code:

test.sh

echo "BEGIN"
while read CMD <&1; do
    [ -z "$CMD" ] && continue
    case "$CMD" in
    start)
            echo "get_start"
            ;;
    stop)
            echo "get_stop"
            ;;
    *)
            echo "get_uknown_command"
            ;;
    esac
    echo "END";
done

When I run it with:

$./test.sh <input.txt

I get my script locked

input.txt

start
stop
sthh

Why my script is locked? How I can fix that?

BTW: If I enter the data manually then the script will not lock.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You're using the wrong file descriptor. 1 is stdout, 0 is stdin.

Change:

while read CMD <&1; do

to:

while read CMD <&0; do

And it will from the file correctly. However, you don't need to do that all since read defaults to using stdin:

while read CMD; do

Also, the -u option can be used to read from a particular file descriptor (at least in bash). So you could do this as well:

while read -u 0 CMD; do
share|improve this answer

File descriptor 1 is stdout or standard output. Which means that you are redirecting read's input to come from standard output. This clearly isn't going to work very well; there will almost certainly never be any input waiting on the standard output for read.

Standard input is file descriptor 0, so if you change <&1 to <&0 on line 2 of your script, it works. Or simply drop that part entirely; read reads from standard input by default (that's pretty much its purpose), so there's no need to explicitly tell it to read from standard input.

If you want to read some particular input interactively and allow the remainder to be redirected from a file (or come through a pipe), you can do read </dev/tty.

And you don't need the semicolon statement separator after the END echo; the newline does just fine.

share|improve this answer

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.