0
if [ ! -z "admin_us" ]
then
newgrp admin_us<< END
 command=` abc.sh `
END
fi
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. – berndbausch Jul 29 '21 at 07:02
  • @berndbausch - I need it from the abc.sh , if newgrp fail , then I will anyways get the exit code – Stay Curious Jul 29 '21 at 07:05
  • what shell are you using? – cas Jul 29 '21 at 07:05
  • @cas - Bash it is – Stay Curious Jul 29 '21 at 07: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. – berndbausch Jul 29 '21 at 07:10

1 Answers1

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)

#!/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?

cas
  • 78,579