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
It is a program that cats the contents of fruit.txt and pipes it to a while statement for standard output.
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!
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.
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
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