Hello
Can anybody tell me why the script below exits the while loop after the first error?
It is part of a script to calculate checksums of files listed in $input_file. I want to capture stderr in a variable, and if there is any error output, write it to a file. I don't want to simply redirect with
Code:
command 2 >> $error_file
since I want to include further debugging info on each line of $error_file.
The script encounters an error when processing the first line of $input_file (this is by design - I'm testing it atm). It then continues executing until it reaches the end of the while block, then exits without going back to the beginning of the while loop. Since the error occurs in a subshell created by $( ), I would expect the while loop to continue until the end of $input_file is reached.
Here is the script with the problem:
Code:
#!/bin/bash
input_file=$1
output_file=sha256sums.txt
cat $input_file | while read i; do
err_output=$(sha256sum $i 2>&1 1>>$output_file);
echo exit status $? i is $i;
done
I run it with an input file consisting of 21 lines of text, each of which is the path to an existing regular file. Its output is one line, corresponding to the first line of the file:
Code:
exit status 1 i is Music/...Off The Bone/01 - Cramps - Human Fly.ra
Here is a very similar script which does not show the same problem:
Code:
#!/bin/bash
input_file=$1
output_file=sha256sums.txt
cat $input_file | while read i; do
# err_output=$(sha256sum $i 2>&1 1>>$output_file);
err_output=$(exit 1)
echo exit status $? i is $i;
done
I run it with the same input file, and it generates output for each line,
Code:
exit status 1 i is [filename]
... [21 times]
Why does the first script stop after the first line? I know it continues to the end of the while block, since the command
Code:
echo exit status $? i is $i;
is executed. According to the bash man page,
Quote:
while list; do list; done
The while command continuously executes the do list as long as
the last command in list returns an exit status of zero.
|
It would appear that all relevant commands return an exit status of zero, and the only one which returns an exit status of 1 should not cause the loop to end.
Hope that that's clear and someone can help!
Thanks
OS