Some little insidious things, I hope to be not overlong:
A first problem was that $?
returns the last exit error code.
So when you execute echo $?
in the following line, you set $?
to a new value, 0
in this case: I see no reason for which the echo
command have to fail.
A second more insidious problem was that the precedent command is a pipe. So the variable to be used is ${PIPESTATUS[0]}
and not $?
. (There is [0]
because it is an array and we want the value stored in the 1st component that is the exit status of the 1st command).
Once again you can store in a variable this value or you can execute immediately after the test. Otherwise the use of other commands will reset again the variable values.
To pause the execution of the script it should enough to write an input line like read -p x < /dev/tty
. To be insidious this time is the standard input flushing that we overcame asking input from tty
.
It is generally safer to use read -r
than read
.
-r raw input - disables interpretation of backslash escapes and line-continuation in the read data
so a code variant should be:
while read -r copy
do
cp -v $copy | tee -a $LOGFILE
# echo $? ${PIPESTATUS[0]} # NOT HERE else you loose it
if [[ ${PIPESTATUS[0]} -ne 0 ]] # $? was referred to the last command.
then # Use ${PIPESTATUS[0]} instead
echo "Error copying files. ${copy} Exiting ..." | tee -a $LOGFILE
# It will wait that you press return
read -p "Press CTRL-C to interrupt, RETURN to continue " x < /dev/tty
# exit 1 # It will not exit: (#) means comment.
fi
done < copy_new_files.tmp
Note: as suggested by chepner The issue with capturing the exit status of cp
can also be fixed by piping the standard output of the while loop to a single call to tee
, rather than the cp
and the echo
individually, that is even more elegant. Of course in that case you will write in the output file all the text printed in the cycle while, and even the not needed "Press CTRL-C to interrupt, RETURN to continue " lines I added.