Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `exit $?` meaningfully different from `exit` in bash?

Tags:

bash

shell

My understanding is that in bash a plain exit will complete a script with the exit status of the last command. But I also have seen people using exit $? and was questioned when I suggested that it had the same behavior.

Is there any meaningful difference between these 2 scripts?

#!/bin/bash
foo
bar
exit 

and

#!/bin/bash
foo
bar
exit $?
like image 577
Ben McCormick Avatar asked Feb 08 '23 17:02

Ben McCormick


1 Answers

There is no difference. When exit is called without a parameter, it will return the exit code of the last command.

Here is the code from GNU bash. If no parameter is given, it returns last_command_exit_value, otherwise it takes the passed in argument, makes sure it is a number, chops off any bits beyond 8 and returns that.

  486 get_exitstat (list)
  487      WORD_LIST *list;
  488 {
  489   int status;
  490   intmax_t sval;
  491   char *arg;
  492 
  493   if (list && list->word && ISOPTION (list->word->word, '-'))
  494     list = list->next;
  495 
  496   if (list == 0)
  497     return (last_command_exit_value);      
  498 
  499   arg = list->word->word;
  500   if (arg == 0 || legal_number (arg, &sval) == 0)
  501     {
  502       sh_neednumarg (list->word->word ? list->word->word : "`'");
  503       return EX_BADUSAGE;
  504     }
  505   no_args (list->next);
  506 
  507   status = sval & 255;
  508   return status;
  509 }
like image 126
woot Avatar answered Feb 20 '23 16:02

woot