if [ ! -z "admin_us" ]
newgrp admin_us<< END
 command=` abc.sh `
echo $?

What we have seen here is, the exit code is always 0, even if the abc.sh fails, what is a better way to fetch the exit code? The last option for me is to save it in a temporary file and read it outside.

  • I would say that the exit status is from the newgrp command, not abc.sh. The question is, when is your code supposed to fail? When newgrp fails, or abc.sh, or both? It's not clear to me, by the way, why you provide input to newgrp. When you run newgrp admin_us, it simply ignores any input. Commented Jul 29, 2021 at 7:02
  • @berndbausch - I need it from the abc.sh , if newgrp fail , then I will anyways get the exit code Commented Jul 29, 2021 at 7:05
  • what shell are you using?
    – cas
    Commented Jul 29, 2021 at 7:05
  • @cas - Bash it is Commented Jul 29, 2021 at 7:06
  • Run abc.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 with newgrp, then exit with exit $abc. Commented Jul 29, 2021 at 7:10

1 Answer 1


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)

if [ 1 == 1 ]; then
newgrp users << END
 exit $?
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')
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?

  • thanks it worked Commented Jul 29, 2021 at 7:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .