Linux get return code

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

  1. Every Linux or Unix command executed by the shell script or user, has an exit status.
  2. The exit status is an integer number.
  3. For the bash shell’s purposes, a command which exits with a zero (0) exit status has succeeded.
  4. A non-zero (1-255) exit status indicates failure.
  5. 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.
  6. 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

Источник

Bash получить код завершения команды в Linux / Unix

Я новый пользователь системы Linux. Как мне получить код завершения команды?

Как получить код вывода или статус команды оболочки Linux или Unix и сохранить его в переменной оболочки?

Введение. Каждая команда оболочки Linux или Unix возвращает состояние, когда она завершается нормально или ненормально.

Например, если скрипт backup.sh не выполнен, и он возвращает код, который сообщает скрипту оболочки отправить электронное письмо админу.

Что такое код вывода в оболочке bash?

Каждая команда Linux или Unix, выполняемая скриптом оболочки или пользователем, имеет статус вывода.

Статус вывода – это целое число.

0 состояние выхода означает, что команда была успешной без каких-либо ошибок.

Ненулевое (1-255 значений) состояние выхода означает, что команда была неудачной.

Как узнать код вывода команды

Вам нужно использовать определенную переменную оболочки с именем $? чтобы получить статус вывода из ранее выполненной команды.

Выведем $? переменной используя команду echo или команду printf:

Из приведенных выше выводов ясно, что код вывода 0 означает, что команда date была успешной.

Кроме того, код вывода – 127 (не ноль), так как команда nonexistant не была успешной.

Bash как получить код завершения команды – Как использовать коды вывода в скриптах оболочки

Итак, как вы сохранить статус вывода команды в переменной оболочки?

Просто назначьте $? в переменную оболочки. Синтаксис:

Как мне установить код вывода для моих собственных скриптов оболочки?

Команда exit вызывает обычное завершение скриптов оболочки.

Вывод из оболочки со статусом N. Синтаксис:

Пример скрипта оболочки для получения кода завершения команды

Заключение

На этой странице показано, как использовать коды вывода в системах на основе Linux или Unix и как получить статус вывода / код команды.

Источник

1. Invoke shell commands

In general, there are three common methods for calling shell commands using C programs in Linux systems: system (), popen (), and exec series functions.

  • Using system () does not require the user to create a process because it is already encapsulated, just add the shell command directly;
  • Use popen () to execute shell commands, the cost is less than system ();
  • Exec requires the user to fork / vfork the process, and then exec the shell commands required.

1.1 system()

Function prototype

Function description
system () will call fork () to generate a subprocess, and the subprocess will call / bin / sh -c string to execute the command represented by the parameter string, and the command will be executed immediately after execution Return to the original calling process. During the call to system (), the SIGCHLD signal will be temporarily suspended, and the SIGINT and SIGQUIT signals will be ignored.

return value
If system () fails when calling / bin / sh, it returns 127, and other failure reasons return -1. If the parameter string is a null pointer (NULL), a non-zero value is returned. If the system () call is successful, the return value after executing the shell command is finally returned, but this return value may also be 127 returned by the failure of the system () call / bin / sh, so it is best to check errno again to confirm the successful execution .

Additional information
Do not use system () when writing a program with SUID / SGID authority, because system () inherits environment variables, which may cause system security problems.

1.2 popen()

Function prototype

Function description
popen () will call fork () to create a child process, and then call / bin / sh -c from the child process to execute the command command parameter. The parameter type can use «r» for reading and «w» for writing. According to this type value, popen () will establish a pipe to the child’s standard output device or standard input device, and then return a file pointer. Then the process can use this file pointer to read the output device of the child process or write to the standard input device of the child process. In addition, except for fclose (), all other functions that use the file pointer (FILE *) operation can also be used.

return value
If successful, the file pointer is returned, otherwise NULL is returned, and the cause of the error is stored in errno.

Precautions
When writing a program with SUID / SGID authority, please avoid using popen () as much as possible, because popen () inherits environment variables, which may cause system security problems.

Examples

1.3 Exec function cluster

Function prototype

Examples
Use vfork () to create a new child process, and then call the exec function family.

2 Get the return result

Above we introduced several methods of calling shell commands in a C program. Among them, we found a problem-although we can know whether the shell command has been executed, sometimes we cannot get the information returned by it. Then, at this time, you can consider the following methods.

2.1 Using temporary files

The easiest way to think of it first should be to redirect the shell command output to a temporary file and read this temporary file in our application to obtain the results of the external command execution.
The code is as follows:

This use uses a temporary file as a link between the application and external commands. In the application, you need to read the file and then delete the temporary file, which is cumbersome. The advantage is that it is simple to implement and easy to understand.

2.2 Use anonymous pipes

In the book «Advanced Programming for UNIX Environment» (APUE), an example of outputting program results to a paging program through anonymous pipes is given. Therefore, we can also use pipes to connect the results of external commands to applications stand up. The method is to fork a child process and create an anonymous pipe, execute shell commands in the child process, and dup its standard output to the input end of the anonymous pipe. The parent process reads from the pipe to obtain the output of the shell command.
The code is as follows:

2.3 Use popen ()

In the example of executing shell commands, we used the popen () function. You may have found it carefully. You can also use popen () to get the result of the command.
The function of this function is to create a pipeline, fork a process, and then execute the shell, and the output of the shell can be obtained by reading the file. This method is recommended to avoid creating temporary files without being limited by the number of output characters.
popen () uses the FIFO pipeline to execute external programs. It determines the input / output direction of the command by whether the type is r or w, and r and w are relative to the pipeline of the command. r means that the command is read from the pipe, w means that the command is output to its stdout through the pipe, and popen () returns the file stream pointer of the FIFO pipe. pclose () is used to close this pointer after use.
Sample code is as follows:

Источник

Читайте также:  Почему windows 10 долго перезагружается что
Оцените статью