- Return и exit, в чем разница?
- Решение
- Разница между return и exit в функциях Bash
- 9 ответов
- выход
- Exit command
- Contents
- Purpose
- Syntax
- Examples
- Exit status at the CLI
- Execute commands based upon the exit status
- Shell script example
- Linux bash exit status and how to set exit status in bash
- More on Linux bash shell exit status codes
- How do I display the exit status of shell command?
- How to store the exit status of the command in a shell variable
- Linux exit status and the conditional/list constructs
- How to use the && and || operators with exit codes
- List of common exit codes for GNU/Linux
- Conclusion
Return и exit, в чем разница?
В чем разница между return и return false/true
Привет всем. Вот подскажите плиз) return; return false; return true; расскажите пожалуйста.
В чем разница между quit(),exit() и terminate() ?
Читал описание класса QThread и не могу понять в чем собствнно различие функций quit(),exit() и.
Операторы Exit, Close, Application.Terminate в чем разница между ними?
Хочу понять разницу между этими операторами. Например, оператор Application.Terminate выходит из.
замена exit(0) на return
необходимо заменить exit(0) из данного куска кода на return в main, используя при этом.
Решение
exit — это функция, которая завершает программу, откуда бы ни была вызвана. return — это оператор, который завершает работу текущей функции (т.е. передаёт управление в точку вызова текущей функции)
Если речь идёт о функции main, то return и exit по смыслу можно считать, что одно и то же. В случае выхода из main’а оператором return управление будет передано в системную часть в точку вызова main, а оттуда будет вызвана функция exit
Однако когда речь идёт о Си++, то разница есть. По оператору return будут вызваны деструкторы всех локальных живых объектов. А по exit — ничего вызвано не будет. Т.е. в C++ return и exit в main’е в общем-то отличаются поведением (в отличие от C)
Источник
Разница между return и exit в функциях Bash
в чем разница между return и exit оператор в функциях BASH относительно кодов выхода?
9 ответов
С man bash on return [n] ;
останавливает выполнение функции и возвращает вызывающему объекту значение, указанное n. Если значение n опущено, возвращается состояние последней команды, выполненной в теле функции.
вызовите выход оболочки со статусом n. Если N опущено, статус выхода-это статус последней выполненной команды. Ловушка на выходе выполняется раньше оболочка заканчивается.
EDIT:
согласно вашему редактированию вопроса, относительно кодов выхода, return не имеет ничего общего с коды выхода. Коды выхода предназначены для приложения/скрипты, а не функции. Поэтому в этом отношении единственное ключевое слово, которое задает код выхода скрипта (тот, который может быть пойман вызывающей программой с помощью $? переменной оболочки) составляет exit .
изменить 2:
мое последнее заявление по поводу exit вызывает некоторые замечания. Это было сделано, чтобы дифференцировать return и exit для понимания OP, и на самом деле, в любой заданная точка скрипта программы / оболочки, exit является единственным способом завершения сценария с кодом выхода из вызывающего процесса.
каждая команда, выполняемая в оболочке, создает локальный «код выхода»: он устанавливает $? переменная к этому коду, и может быть использована с if , && и другие операторы для условного выполнения других команд.
эти коды выхода (и стоимостью $? variable) сбрасываются при каждом выполнении команды.
кстати, код выхода последней команды, выполняемой скриптом, используется в качестве кода выхода самого скрипта, как видно вызывающему процессу.
наконец, функции при вызове действуют как команды оболочки в отношении кодов выхода. Код выхода функции (внутри функция) устанавливается с помощью return . Итак, когда в функции return 0 выполняется, выполнение функции завершается, давая код выхода 0.
return приведет к выходу текущей функции из области видимости, в то время как exit приведет к завершению сценария в точке, где он вызывается. Вот пример программы, которая поможет объяснить это:
выход
Я не думаю, что кто действительно полностью ответил на вопрос, потому что они не описывают, как они используются. Хорошо, я думаю, мы знаем, что exit убивает скрипт, где бы он ни вызывался, и вы можете назначить ему статус, такой как exit или exit 0 или exit 7 и так далее. Это можно использовать для определения того, как сценарий был вынужден остановиться, если вызывается другим сценарием и т. д. Достаточно на выходе.
return при вызове вернет значение, указанное для указания функции поведение, обычно 1 или 0. Например:
в этом примере тест может использоваться для указания, был ли найден каталог. обратите внимание, что ничего после возврата не будет выполняться в функции. 0 истинно, но false равно 1 в оболочке, отличающейся от других прогов.
Примечание: функция isdirectory предназначена только для учебных целей. Это не должно быть так, как вы выполняете такую опцию в реальном скрипте.
помните, что функции являются внутренними для скрипта и обычно возвращаются оттуда, откуда они были вызваны с помощью оператора return. Вызов внешнего скрипта-это совсем другое дело, и скрипты обычно завершаются инструкцией exit.
разница «между оператором return и exit в функциях BASH относительно кодов выхода» очень мала. Оба возвращают статус, а не значения per se. Состояние ноль указывает на успех, в то время как любой другой статус (От 1 до 255) указывает на сбой. Оператор return вернется в сценарий, откуда он был вызван, в то время как оператор exit завершит весь сценарий, с которого он встречается.
Если ваша функция просто заканчивается без оператора return, статус последней выполненной команды возвращается как код состояния (и будет помещен в $? ).
помните, возврат и выход возвращают код состояния от 0 до 255, доступный в $? . Нельзя вставьте что-нибудь еще в код состояния (например, Верните «cat»); это не сработает. Но сценарий может передать 255 различных причин сбоя с помощью кодов состояния.
вы можете установить переменные, содержащиеся в вызывающем скрипте, или результаты Эха в функции и использовать подстановку команд в вызывающем скрипте; но цель возврата и выхода-передать коды состояния, а не значения или результаты вычислений, как можно было бы ожидать на языке программирования, таком как C.
иногда, вы запускаете скрипт через . или source .
если вы включили exit на a.sh , он не просто завершит скрипт,но и завершит сеанс оболочки.
если вы включите return на a.sh , Он просто перестает обрабатывать скрипт.
простыми словами (в основном для новичков в кодировании), мы можем сказать,
также, если вы заметили, это очень основное, но.
exit завершить текущий процесс; С кодом выхода или без него, считайте это системой больше, чем функцией программы. Обратите внимание, что при поиске, exit завершит оболочку, однако, при запуске будет просто exit сценарий.
return функции вернитесь к инструкции после вызова, с кодом возврата или без него. return является необязательным и неявным в конце функции. return только может быть используется внутри функции.
я хочу добавить, что в то время как источник, это не просто exit скрипт изнутри функции, не убивая оболочку. Я думаю, пример лучше на тестовом скрипт
test -и — оболочка закроет.
только test завершится, и появится подсказка.
решение заключить потенциально процедура в ( и )
теперь, только в обоих случаях test выйдет.
прежде всего, return является ключевым словом и exit мой друг-функции.
тем не менее, вот самое простое объяснение.
return Он возвращает значение из функции.
exit Он выходит из текущей оболочки или покидает ее.
вопрос OP: В чем разница между оператором return и exit в функциях BASH относительно кодов выхода?
Firtly, некоторым требуется уточнение:
- оператор (return|exit) не требуется для завершения выполнения (функции|оболочки). A (функция|оболочка) завершится, когда он достигнет конца своего списка кода, даже без оператора (return|exit).
- оператор (return|exit) не требуется для передачи значения назад от завершенного (функция / оболочка). Каждый процесс имеет встроенную переменную $? который всегда имеет числовое значение. Это специальная переменная, которая не может быть установлена как «?=1», но устанавливается только специальными способами (см. ниже *). Стоимость $? после последней команды, выполняемой в (называемой function | sub shell), возвращается значение (function caller | parent shell). Это верно, является ли последняя выполненная команда («return [n]»| «exit [n]») или простой («return» или что-то еще else, который является последней командой в вызываемом коде функций.
в приведенном выше списке пуль выберите » (x / y)» либо всегда первый элемент, либо всегда второй элемент, чтобы получить инструкции о функциях & return или shells & exit соответственно.
что ясно, что они оба разделяют общее использование специальной переменной $? передавать значения вверх после их завершения.
* теперь для специальных способов, что $? может быть set:
- когда вызываемая функция завершается и возвращается к вызывающему объекту, тогда$? в caller будет равно конечному значению $? в завершенной функции.
- когда родительская оболочка impliciltly или явно ожидает на одной суб-оболочке и освобождается путем завершения этой суб-оболочки, то $? в родительской оболочке будет равно конечному значению $? в завершенной оболочке sub.
- некоторые встроенные функции могут изменять $? в зависимости от их результат. Но некоторые нет.
- встроенные функции «return» и «exit», когда за ними следует числовой аргумент both $? с аргументом и прекратить выполнение.
стоит отметить, что $? можно назначить значение, вызвав exit в sub shell, например:
Источник
Exit command
Sometimes we need to stop the execution of our script when a condition is satisfied. For example, if tar command not installed, stop the execution of our shell script. We can also take action based on the exit code of the command. Say if ping command is successful, continue with script or exit with an error. Let us see how to use the exit command and the exit statuses in our scripts.
Contents
Purpose
Exit the bash shell or shell script with a status of N.
Syntax
The syntax is as follows:
- The exit statement is used to exit from the shell script with a status of N.
- Use the exit statement to indicate successful or unsuccessful shell script termination.
- The value of N can be used by other commands or shell scripts to take their own action.
- If N is omitted, the exit status is that of the last command executed.
- Use the exit statement to terminate shell script upon an error.
- If N is set to 0 means normal shell exit.
Examples
Create a shell script called exitcmd.sh:
Save and close the file. Run it as follows:
To see exit status of the script, enter (see the exit status of a command for more information about special shell variable $?) :
Exit status at the CLI
Exit status is not limited to shell script. Every time command terminated shell gets an exit code indicating success or failure of the command. Hence we can use the particular bash variable $? to get the exit status of the command. For instance:
In this example, we will see the exit status of the last command (command3) only:
Execute commands based upon the exit status
Run command2 if command1 is successful using Logical AND ( && ) operator:
For example, if wget command found in execute the echo command
Similarly, bar command is executed if, and only if, foo command returns a non-zero exit status using Logical OR operator:
Therefore we can combine bash Exit command and exit codes to build quick logic as follows:
We can group commands as a unit as follows:
Shell script example
- Any non zero value indicates unsuccessful shell script termination.
- Create a shell script called datatapebackup.sh:
Save and close the file. Run it as follows:
All of our shell commands return an exit code when terminated successfully or abnormally. We can use the exit command in our shell script to provide the exit code. We also learned how to harness the exit status’s power to build logic in a shell script or at the command line.
Источник
Linux bash exit status and how to set exit status in bash
C an you explain bash exit status code? How do I set bash exit status in my Linux shell scripts?
Each Linux or Unix command returns a status when it terminates normally or abnormally. You can use value of exit status in the shell script to display an error message or run commands. For example, if tar command is unsuccessful, it returns a code which tells the shell script to send an e-mail to sysadmins.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash running on Linux, macOS or Unix |
Est. reading time | 3 minutes |
More on Linux bash shell exit status codes
- Every Linux or Unix command executed by the shell script or user, has an exit status.
- The exit status is an integer number.
- For the bash shell’s purposes, a command which exits with a zero (0) exit status has succeeded.
- A non-zero (1-255) exit status indicates failure.
- If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.
- All of the Bash builtins return exit status of zero if they succeed and a non-zero status on failure.
How do I display the exit status of shell command?
You can use special shell variable called $? to get the exit status of the previously executed command. To print $? variable use the echo command/printf command. The syntax is:
command
echo $?
OR
/path/to/script.sh
command
date
echo $?
## OR use the printf command ##
printf «%d\n» $?
## run non-existence command ##
foobar13535
## display status code ##
echo $?
How to store the exit status of the command in a shell variable
Assign $? to a shell variable. The syntax is:
Linux exit status and the conditional/list constructs
A simple shell script to locate host name (findhost.sh)
How to use the && and || operators with exit codes
If a dir named “/tmp/foo” not found create it:
[ ! -d «/tmp/foo» ] && mkdir -p «/tmp/foo»
For example, show usage syntax when filename not passed as the command line arg:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Here is another shell script that shows usage:
List of common exit codes for GNU/Linux
Exit Code | Description |
---|---|
0 | Success |
1 | Operation not permitted |
2 | No such file or directory |
3 | No such process |
4 | Interrupted system call |
5 | Input/output error |
6 | No such device or address |
7 | Argument list too long |
8 | Exec format error |
9 | Bad file descriptor |
10 | No child processes |
11 | Resource temporarily unavailable |
12 | Cannot allocate memory |
13 | Permission denied |
14 | Bad address |
15 | Block device required |
16 | Device or resource busy |
17 | File exists |
18 | Invalid cross-device link |
19 | No such device |
20 | Not a directory |
21 | Is a directory |
22 | Invalid argument |
23 | Too many open files in system |
24 | Too many open files |
25 | Inappropriate ioctl for device |
26 | Text file busy |
27 | File too large |
28 | No space left on device |
29 | Illegal seek |
30 | Read-only file system |
31 | Too many links |
32 | Broken pipe |
33 | Numerical argument out of domain |
34 | Numerical result out of range |
35 | Resource deadlock avoided |
36 | File name too long |
37 | No locks available |
38 | Function not implemented |
39 | Directory not empty |
40 | Too many levels of symbolic links |
42 | No message of desired type |
43 | Identifier removed |
44 | Channel number out of range |
45 | Level 2 not synchronized |
46 | Level 3 halted |
47 | Level 3 reset |
48 | Link number out of range |
49 | Protocol driver not attached |
50 | No CSI structure available |
51 | Level 2 halted |
52 | Invalid exchange |
53 | Invalid request descriptor |
54 | Exchange full |
55 | No anode |
56 | Invalid request code |
57 | Invalid slot |
59 | Bad font file format |
60 | Device not a stream |
61 | No data available |
62 | Timer expired |
63 | Out of streams resources |
64 | Machine is not on the network |
65 | Package not installed |
66 | Object is remote |
67 | Link has been severed |
68 | Advertise error |
69 | Srmount error |
70 | Communication error on send |
71 | Protocol error |
72 | Multihop attempted |
73 | RFS specific error |
74 | Bad message |
75 | Value too large for defined data type |
76 | Name not unique on network |
77 | File descriptor in bad state |
78 | Remote address changed |
79 | Can not access a needed shared library |
80 | Accessing a corrupted shared library |
81 | .lib section in a.out corrupted |
82 | Attempting to link in too many shared libraries |
83 | Cannot exec a shared library directly |
84 | Invalid or incomplete multibyte or wide character |
85 | Interrupted system call should be restarted |
86 | Streams pipe error |
87 | Too many users |
88 | Socket operation on non-socket |
89 | Destination address required |
90 | Message too long |
91 | Protocol wrong type for socket |
92 | Protocol not available |
93 | Protocol not supported |
94 | Socket type not supported |
95 | Operation not supported |
96 | Protocol family not supported |
97 | Address family not supported by protocol |
98 | Address already in use |
99 | Cannot assign requested address |
100 | Network is down |
101 | Network is unreachable |
102 | Network dropped connection on reset |
103 | Software caused connection abort |
104 | Connection reset by peer |
105 | No buffer space available |
106 | Transport endpoint is already connected |
107 | Transport endpoint is not connected |
108 | Cannot send after transport endpoint shutdown |
109 | Too many references |
110 | Connection timed out |
111 | Connection refused |
112 | Host is down |
113 | No route to host |
114 | Operation already in progress |
115 | Operation now in progress |
116 | Stale file handle |
117 | Structure needs cleaning |
118 | Not a XENIX named type file |
119 | No XENIX semaphores available |
120 | Is a named type file |
121 | Remote I/O error |
122 | Disk quota exceeded |
123 | No medium found |
125 | Operation canceled |
126 | Required key not available |
127 | Key has expired |
128 | Key has been revoked |
129 | Key was rejected by service |
130 | Owner died |
131 | State not recoverable |
132 | Operation not possible due to RF-kill |
133 | Memory page has hardware error |
The perror command explain error codes which is part of MySQL/MariaDB package:
perror 0
perror 1
Conclusion
This page explained bash exit status and related commands. For more info see bash shell man page here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник