[LINUX] A story that did not end with exit when turning while with pipe input

I wrote such a program in bash

fruits.txt


apple
banana
orange
#!/bin/bash

cat fruits.txt | while read LINE do
    echo ${LINE}
    if [ $? -ne 0 ] ; then
        echo "error:${LINE}"
        exit 1;
    fi
done

echo "Successful completion!"
done

Commentary

It is a program that cats the contents of fruit.txt and pipes it to a while statement for standard output.

Try to run

For example, if banana echo fails, the expected output is:

apple
error:banana

However, the actual output is as follows. The script did not end after the error, and the subsequent processing continues.

apple
error:banana
orange
Successful completion!

Cause

When piped to a while statement, the while loop is a child process of the original script It will be executed. Therefore, even if you do exit 1, only the child process will end, The main process will continue.

Solution 1_Pick up the return value of the child process

The parent process picks up the return value 1 of the child process and terminates the parent process abnormally.

cat fruits.txt | while read LINE do
    echo ${LINE}
    if [ $? -ne 0 ] ; then
        echo "error:${LINE}"
        exit 1;
    fi
done

if [ $? -ne 0 ] ; then
    exit 1;
fi

Solution 2 Use the _for statement

Specifying the result of cat in the list of for statements will solve the problem. If you do this, you don't need to define a variable to put the result of cat separately, so it's smart.

for FRUIT in `cat fruits.txt`; do
    echo ${FRUIT} 
done

Recommended Posts

A story that did not end with exit when turning while with pipe input
A story that stumbled when I made a chatbot with Transformer
The story that `while queue` did not work in python
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
A story that I was addicted to when I made SFTP communication with python
A story that failed when trying to remove the suffix from the string with rstrip
There is a pattern that the program did not stop when using Python threading
The story that sendmail that can be executed in the terminal did not work with cron
A story that struggled with the common set HTTP_PROXY = ~
Create a chatbot that supports free input with Word2Vec
The story that yapf did not work in vscode
A story that I did not know how to load a mixin when making a front with the django app [Beginners learn python with a reference book in one hand]
A story that went missing when I specified a path starting with a tilde (~) in python open
A story that stumbled when using pip in a proxy environment
Use a macro that runs when saving python with vscode
A story that didn't work when I tried to log in with the Python requests module