简体   繁体   中英

Bash-Shell Script aborts without error

On Debian is the following code working, but on CentOS it just aborts without any errors. What is the error? I can't understand it.

    echo "Test 1"
    ANSWER=""
    read -p "Enter y or n " ANSWER;
    echo "Test 2"

The output looks allways like that:

    Test 1

I also tried the read command without the parameter -p, but that's also not working:

    echo "Test 1"
    ANSWER=""
    echo "Enter y or n "
    read ANSWER;
    echo "Test 2"

Output:

    Test 1
    Enter y or n

If I execute the command at the command line is it working, how it should. The script has following "headline": #!/bin/bash

Can somebody help?

try this

#!/bin/bash

echo "Test 1"
read -p "Enter y/n: " ANSWER
echo " Test 2: ${ANSWER}"

You didn't need a close on the end of answer.

@ user2966991 - The script which reads from stdin is inside a bigger while loop which reads a file through stdin. This will not work. Try redirecting your stdin to a different file handler.

Consider this sample code. This will not work becuase both the while loop and read are reading from stdin.

#!/bin/bash
cat samplefile | while read line; do
    read -p "$line (y/n)?" ANSWER
done

Now consider this other code.

#!/bin/bash
# save stdin to file descriptor 5
exec 5<&0

cat samplefile | while read line; do
    read -p "$line (y/n)?" ANSWER <&5
done

# restore stdin and close file descriptor 5
exec 0<&5 5>&-

Personally I prefer input redirection than pipe.

cat file | while read var; do
...
done

can be written as

while read var; do
...
done < file

Next time please post your script here or you will not get any answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM