The safe way to pass code to functions is... to encapsulate that code in another function.
run() {
local output
if output=$("$@"); then
printf 'OK. (?%s?)
' "$output";
else
printf 'Failed! (?%s?)
' "$output";
fi
}
printf 'Setting up ?uni? as system group...'
step1() {
if [ ! "$(getent group uni)" ]; then
sudo addgroup --system uni;
else
echo 'Group exists.';
fi
}
run step1
If your code didn't involve flow control operators (and otherwise fit into the definition of a "simple command"), you wouldn't even need to do that; with the above run
definition (using "$@"
instead of $1
),
run sudo addgroup --system uni
...would work correctly as-is.
Using either eval
or sh -c
exposes you to serious security problems; see BashFAQ #48 for a high-level overview, and see BashFAQ #50 for a discussion of why code shouldn't be passed around as text (and preferred ways to avoid the need to do so in the first place!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…