I have a loop that checks for certain criteria for whether or not to skip to the next iteration (A). I realized that if I invoke a function (skip
) that calls continue
, it is as if it is called in a sub-process for it does not see the loop (B). Also the proposed workaround that relies on eval
-uating a string does not work (C).
# /usr/bin/bash env
skip()
{
echo "skipping : $1"
continue
}
skip_str="echo "skipping : $var"; continue"
while read -r var;
do
if [[ $var =~ ^bar$ ]];
then
# A
# echo "skipping : $var"
# continue
# B
# skip "$var" # continue: only meaningful in a for',
while', or `until' loop
# C
eval "$skip_str"
fi
echo "processed: $var"
done < <(cat << EOF
foo
bar
qux
EOF
)
Method C:
$ source ./job-10.sh
processed: foo
skipping :
processed: qux
Also see:
Do functions run as subprocesses in Bash?
PS1: could someone remind me why < <
rather than <
is needed after done
?
PS2: no tag found for while
hence for
/usr/bin/env bash
or/bin/bash
but not/usr/bin/bash env
. – terdon Apr 08 '21 at 18:01skip_str
you end up evaluating$var
there and then, so when you calleval
there's no variable to evaluate. But this is really poor practice anyway so don't do it like this – Chris Davies Apr 08 '21 at 18:02<( command )
runscommand
, stores the stdout in a tmp file, and substitutes itself with the tmp filename. The preceding<
is a normal redirect that attaches that tmp filename to stdin of thewhile do done
, and is inherited by all of its child processes (in this case theread
built-in). – Paul_Pedant Apr 08 '21 at 18:11