I've a bash script with some file manipulations and I would like to process a loop until the end of the block after pressing CTRL+C. I've made an example:
#!/bin/bash
# Register signal handler
ABORT=0;
trap ABORT=1 SIGINT;
# Create temp dir
TEMPDIR=$(mktemp -d -t $0);
# Helper functions
function do_other_stuff {
true;
}
# Process files
for ((COUNTER = 0; COUNTER < 3 && ABORT == 0; COUNTER++)); do
FILE=/some/directory/$COUNTER.txt;
BASE=$(basename $FILE);
cp $FILE $TEMPDIR;
> $FILE;
do_other_stuff;
cp $TEMPDIR/$BASE $FILE;
rm $TEMPDIR/$BASE;
done;
rm -rf $TEMPDIR;
这似乎工作得很好,但我注意到,有时语句中的 BASE
BASE=$(basename $FILE);
如果陷阱恰好发生在 basename 命令期间,则不会设置。这会导致错误cp
并遵循命令。
我是不是错过了什么? bash 的目的是如何从陷阱中恢复?有没有其他解决方案具有相同的效果?
代替
BASE=$(basename $FILE);
用这个代替:
BASE=${FILE##*/}
将工作函数放置在远离处理 SIGINT 的界面的后台也是一个好主意。只是避免要求其中的输入。还要始终正确引用您的变量。
#!/bin/bash
# Register signal handler
ABORT=0;
trap ABORT=1 SIGINT;
# Create temp dir
TEMPDIR=$(mktemp -d -t $0);
# Helper functions
function do_other_stuff {
true;
}
# Process files
for ((COUNTER = 0; COUNTER < 3 && ABORT == 0; COUNTER++)); do
(
FILE=/some/directory/$COUNTER.txt
BASE=${FILE##*/}
cp "$FILE" "$TEMPDIR"
> "$FILE"
do_other_stuff
cp "$TEMPDIR/$BASE" "$FILE"
rm "$TEMPDIR/$BASE"
) &
CPID=$!
# Handle SIGINT but don't end the loop until subprocess finishes its work.
while kill -s 0 CPID &>/dev/null; do ## Checks if subprocess is still there.
# Wait if yes.
wait "$CPID"
done
done
rm -rf "$TEMPDIR"
这将快速中止操作:
# Process files
for ((COUNTER = 0; COUNTER < 3 && ABORT == 0; COUNTER++)); do
(
FILE=/some/directory/$COUNTER.txt
BASE=${FILE##*/}
cp "$FILE" "$TEMPDIR"
> "$FILE"
do_other_stuff
cp "$TEMPDIR/$BASE" "$FILE"
rm "$TEMPDIR/$BASE"
) &
CPID=$!
while
wait "$CPID"
if [[ ABORT -eq 1 ]]; then
kill -s ABRT "$CPID" &>/dev/null
break
fi
kill -s 0 "$CPID" &>/dev/null
do
continue
done
done
rm -rf "$TEMPDIR"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)