2015-10-25 27 views
4

我的理解是,在bash中,一個普通的exit將完成一個腳本,其中包含最後一個命令的退出狀態。但我也見過使用exit $?的人,並且當我提出它有相同的行爲時被質疑。

這兩個腳本之間有什麼有意義的區別嗎?

#!/bin/bash 
foo 
bar 
exit 

#!/bin/bash 
foo 
bar 
exit $? 
+0

請參閱** [exit-status.html](http://tldp.org/LDP/abs/html/exit-status.html)**。 「相當於一個光禿的'exit'就是'exit $?',甚至只是省略了exit。」 – amdixon

+0

否;你可以省略明確的'出口',它仍然基本相同。 –

回答

8

沒有區別。當沒有參數調用exit時,它將返回最後一個命令的退出代碼。

這是GNU bash的代碼。如果沒有給出參數,則返回last_command_exit_value,否則它將傳入參數,確保它是一個數字,將任何超過8的位截斷並返回。

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 } 
相關問題