2

How can I get the exit code from command exec ?

This is the sample code. For the others commands it works but not for exec.

exec "somethings"
if [ $? == 0 ];
then
    echo -e "Done\n"
    exit 0
else
    echo -e "error\n"
    exit 1
fi
Rayleigh
  • 845
Bombo
  • 23
  • 1
    exec (with a command, not just redirections) never returns, but replaces the current program with another. There's no way to get its exit code. What are you trying to do exactly? –  Jan 23 '20 at 10:32
  • By definition exec will not return an exit code to the shell if it succeeds, as it replaces the script. – icarus Jan 23 '20 at 10:32
  • i don't know that the exec doesn't have the return code. I must run the "command" with exec created by a concatenation by strings. – Bombo Jan 23 '20 at 10:35
  • 1
    So in reality your question should be How do I run a command line that I need to construct using string concatenation?. To which You use exec. is the wrong answer. – JdeBP Jan 23 '20 at 11:06
  • @JdeBP practically yes. – Bombo Jan 23 '20 at 11:11

1 Answers1

2

When I had the same question this helped me.

When you successfully use exec, the exec'd program replaces your shell. The exec'd program's exit status is sent back to the parent process that executed your shell.

The only way that exec's exit status can be interpreted by the line following exec is if the exec calls fails, normally only if the command requested does not exist or if the file is not executable. This does not include option parsing problems, since those are parsed by the exec'd program once it is started.

If you want your shell to interpret the exit code of a program, you cannot use exec to do it. Just run the program in your shell, and when it finishes you can consult the exit status.

ReferHere

Abishek J
  • 170