Your heredoc script needs to exit with $? as the exit code.
e.g. minimum-working example (that assumes my UID is a member of users
and doesn't require your abc.sh
script (uses false
instead)
#!/bin/bash
if [ 1 == 1 ]; then
newgrp users << END
command=$(false)
exit $?
END
fi
echo $?
NOTE: newgrp
forks a new shell, and can't change the value of $command
in its parent. You probably want something more like:
if [ ! -z "admin_us" ]; then
command=$(newgrp admin_us <<<'abc.sh')
fi
echo "$?"
echo "$command"
BTW, don't use backticks. Use $(...)
instead. backticks are deprecated, only retained for backwards-compatibility with older shells/scripts. See Have backticks (i.e. cmd
) in *sh shells been deprecated?
newgrp
command, notabc.sh
. The question is, when is your code supposed to fail? Whennewgrp
fails, orabc.sh
, or both? It's not clear to me, by the way, why you provide input tonewgrp
. When you runnewgrp admin_us
, it simply ignores any input. – berndbausch Jul 29 '21 at 07:02Bash
it is – Stay Curious Jul 29 '21 at 07:06abc.sh
, assign its exit code to a variable e.g.abc
and its output to another variable e.g.output
. Use$output
to perform whatever you want withnewgrp
, then exit withexit $abc
. – berndbausch Jul 29 '21 at 07:10