Linux show exit code

How to get exit code and stdout of a linux command at the same time

I execute a curl [url] command in a Linux shell script. I want to get this command’s exit code and its output at the same time without using a temporary file. Is there any method to do that?

I left an answer that fulfills your criteria of output and exit code without a temp file. Please edit your question with more details if you had something more specific in mind.

3 Answers 3

I’m assuming the problem is that you have an intermediary command that’s supplanting the exit code of the last command.

To get around this, just store the exit code and stdout in variables:

OUTPUT=$(curl example.org) EXIT_CODE=$? 

then you can simply output these either in the same line:

or call them separately as needed.

(I don’t have enough reputation points to comment on user559633’s answer.)

Apparently this won’t work if you send STDOUT to a local variable:

#!/bin/bash function test1 () < OUTPUT=$( ping -c 1 -W 1 blah.org ) EXIT_CODE=$? echo "$EXIT_CODE: $OUTPUT" >function test2 () < local OUTPUT=$( ping -c 1 -W 1 blah.org ) EXIT_CODE=$? echo "$EXIT_CODE: $OUTPUT" >test1 test2 
# ./test.sh 1: PING blah.org (205.150.150.140) 56(84) bytes of data. --- blah.org ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms 0: PING blah.org (205.150.150.140) 56(84) bytes of data. --- blah.org ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms 

Note the exitcode from test1 is 1, but for test2, it’s 0.

EDIT: It seems that separating the local declaration from the assignment takes care of this:

#!/bin/bash function test1 () < OUTPUT=$( ping -c 1 -W 1 blah.org ) EXIT_CODE=$? echo "$EXIT_CODE: $OUTPUT" >function test2 () < local OUTPUT OUTPUT=$( ping -c 1 -W 1 blah.org ) EXIT_CODE=$? echo "$EXIT_CODE: $OUTPUT" >test1 test2 
1: PING blah.org (205.150.150.140) 56(84) bytes of data. --- blah.org ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms 1: PING blah.org (205.150.150.140) 56(84) bytes of data. --- blah.org ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms 

Источник

Linux and Unix exit code tutorial with examples

Tutorial on using exit codes from Linux or UNIX commands. Examples of how to get the exit code of a command, how to set the exit code and how to suppress exit codes.

Exit codes in Unix and Linux

  • August 7, 2016
  • Updated May 24, 2023

What is an exit code in the UNIX or Linux shell? ¶

An exit code, or sometimes known as a return code, is the code returned to a parent process by an executable. On POSIX systems the standard exit code is 0 for success and any number from 1 to 255 for anything else.

Exit codes can be interpreted by machine scripts to adapt in the event of successes of failures. If exit codes are not set the exit code will be the exit code of the last run command.

How to get the exit code of a command ¶

To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command.

cat file.txt hello world echo $? 0 

The command was successful. The file exists and there are no errors in reading the file or writing it to the terminal. The exit code is therefore 0 .

Читайте также:  Запущенные процессы linux ubuntu

In the following example the file does not exist.

cat doesnotexist.txt cat: doesnotexist.txt: No such file or directory echo $? 1 

The exit code is 1 as the operation was not successful.

How to use exit codes in scripts ¶

To use exit codes in scripts an if statement can be used to see if an operation was successful.

#!/bin/bash  cat file.txt  if [ $? -eq 0 ] then  echo "The script ran ok"  exit 0 else  echo "The script failed" >&2  exit 1 fi 

If the command was successful the exit code will be 0 and ‘The script ran ok’ will be printed to the terminal.

How to set an exit code ¶

To set an exit code in a script use exit 0 where 0 is the number you want to return. In the following example a shell script exits with a 1 . This file is saved as exit.sh .

Executing this script shows that the exit code is correctly set.

What exit code should I use? ¶

The Linux Documentation Project has a list of reserved codes that also offers advice on what code to use for specific scenarios. These are the standard error codes in Linux or UNIX.

  • 1 — Catchall for general errors
  • 2 — Misuse of shell builtins (according to Bash documentation)
  • 126 — Command invoked cannot execute
  • 127 — “command not found”
  • 128 — Invalid argument to exit
  • 128+n — Fatal error signal “n”
  • 130 — Script terminated by Control-C
  • 255\* — Exit status out of range

How to suppress exit statuses ¶

Sometimes there may be a requirement to suppress an exit status. It may be that a command is being run within another script and that anything other than a 0 status is undesirable.

In the following example a file is printed to the terminal using cat. This file does not exist so will cause an exit status of 1 .

To suppress the error message any output to standard error is sent to /dev/null using 2>/dev/null .

If the cat command fails an OR operation can be used to provide a fallback — cat file.txt || exit 0 . In this case an exit code of 0 is returned even if there is an error.

Combining both the suppression of error output and the OR operation the following script returns a status code of 0 with no output even though the file does not exist.

#!/bin/bash  cat 'doesnotexist.txt' 2>/dev/null || exit 0 

Further reading ¶

Tags

Can you help make this article better? You can edit it here and send me a pull request.

See Also

  • Linux and Unix cat command tutorial with examples
    Aug 4, 2016
    Tutorial on using cat, a UNIX and Linux command for concatenating files and printing to standard output. Examples of showing the contents of a file, appending one file to another, and combining multiple files into one.
  • Linux and Unix grep command tutorial with examples
    Aug 3, 2016
    Tutorial using grep, a UNIX and Linux command to print lines matching a pattern. Examples of finding text in a file, printing line numbers, counting the number of matches, searching recursively and ignoring case sensitivity.
  • Linux and Unix tee command tutorial with examples
    Jul 28, 2016
    Tutorial on using tee, a UNIX and Linux command for copying standard input to standard output and making a copy to one or more files. Examples of writing to a file, appending to a file and writing to a privileged file.
Читайте также:  Install steam on linux mint

Источник

How to configure bash to print exit status for every command?

Every command run in bash returns with an exit code. Whenever I type a command on bash prompt, I want it to show the exit status, i.e., echo $? e.g., if I run echo «hello»; on bash prompt, the output should be:

linux@linux$ hello linux@linux$ 0 

3 Answers 3

The exit code from the last executed command is stored in the $? environment variable. So you just can add this variable to the default command prompt and you will always have the exit code printed there. The prompt is stored in the $PS1 environment variable. It is initially set in the /etc/bash.bashrc script and later in the $HOME/.bashrc .

So edit the line in $HOME/.bashrc ( /etc/bash.bashrc would be system wide) from it’s default value:

So the default prompt in changed to:

The 0 in the brackets is your exit code, see:

user@host:~[0] $ ls user@host:~[0] $ ls /root/ ls: cannot open directory /root/: Permission denied user@host:~[2] $ ^C user@host:~[130] $ 

I tried doing it but for the bash at hand, its not working. it always shows [0] for the machine I am working on.

Are you sure that you run a bash? Can you copy the output of readlink /proc/$$/exe please? 0 means no error, have you tried something that gives an error: ^C or false or asdasdasd ?

@chaos I have my PS1 as PS1=$(printf «%s\\\\u@\h:%s%s\w[$?]$%s » «$yellow» «$end» «$blue» «$end») , but it just shows 0 all the time. Any idea why?

@max It’s because your $? is already expanded to 0 when setting your PS1 . Do echo $PS1 and you’ll see. You have to either use single quotes, or escape it like \$? .

Another way that I picked from the Arch Wiki was to use trap :

$ ( exit 1 ) code 1 $ some-non-existent-command some-non-existent-command: command not found code 127 $ 

That doesn’t quite meet the OP’s requirements, since he wants to print the exit status even if it’s zero — but it’s exactly what I’ve been looking for.

Running the top code through shellcheck prints a couple of warnings: (1) This apostrophe terminated the single quoted string! (2) This word is outside of quotes. Did you intend to ‘nest ‘»‘single quotes'»‘ instead’?. If code is updated to: echo -e «\e[1;33m code $? \e[m\n» it solves the chellcheck warnings and still works exactly as intended.

If using double quotes, then you have to add a backslash to escape the $ :

0 > echo 'ok' ok 0 > bogus bogus: command not found 127 > 

An even better way is to only print the exit code when it is non-zero.

PS1='$> ' # single quote example PS1="\$> " # double quote example (requires extra backslash) 
> echo 'ok' ok > bogus bogus: command not found 127> 

Explanation: $ is a bash parameter expansion that means remove the shortest matching pattern from the front of $var. So in this case, we are removing 0 from the front of $? , which would effectively truncate an exit code of 0 .

If using double quotes, $? would be substituted when PS1 is set, instead of being evaluated each time. Do echo $PS1 to confirm you don’t have a hardcoded value in PS1 .

Источник

How do I get the list of exit codes (and/or return codes) and meaning for a command/utility?

Is there a way I can do what stated in the title from the terminal commands, or will I have to look into the codes?

4 Answers 4

Exit codes indicates a failure condition when ending a program and they fall between 0 and 255. The shell and its builtins may use especially the values above 125 to indicate specific failure modes, so list of codes can vary between shells and operating systems (e.g. Bash uses the value 128+N as the exit status). See: Bash — 3.7.5 Exit Status or man bash .

Читайте также:  No such process linux

In general a zero exit status indicates that a command succeeded, a non-zero exit status indicates failure.

To check which error code is returned by the command, you can print $? for the last exit code or $ which gives a list of exit status values from pipeline (in Bash) after a shell script exits.

There is no full list of all exit codes which can be found, however there has been an attempt to systematize exit status numbers in kernel source, but this is main intended for C/C++ programmers and similar standard for scripting might be appropriate.

Some list of sysexits on both Linux and BSD/OS X with preferable exit codes for programs (64-78) can be found in /usr/include/sysexits.h (or: man sysexits on BSD):

0 /* successful termination */ 64 /* base value for error messages */ 64 /* command line usage error */ 65 /* data format error */ 66 /* cannot open input */ 67 /* addressee unknown */ 68 /* host name unknown */ 69 /* service unavailable */ 70 /* internal software error */ 71 /* system error (e.g., can't fork) */ 72 /* critical OS file missing */ 73 /* can't create (user) output file */ 74 /* input/output error */ 75 /* temp failure; user is invited to retry */ 76 /* remote error in protocol */ 77 /* permission denied */ 78 /* configuration error */ /* maximum listed value */ 

The above list allocates previously unused exit codes from 64-78. The range of unallotted exit codes will be further restricted in the future.

However above values are mainly used in sendmail and used by pretty much nobody else, so they aren’t anything remotely close to a standard (as pointed by @Gilles).

In shell the exit status are as follow (based on Bash):

  • 1 — 125 — Command did not complete successfully. Check the command’s man page for the meaning of the status, few examples below:
  • 1 — Catchall for general errors
$ let "var1 = 1/0"; echo $? -bash: let: var1 = 1/0: division by 0 (error token is "0") 1 

Missing keyword or command, or permission problem (and diff return code on a failed binary file comparison).

$ curl foo; echo $? curl: (6) Could not resolve host: foo 6 
$ /dev/null $ /etc/hosts; echo $? -bash: /etc/hosts: Permission denied 126 
$ foo; echo $? -bash: foo: command not found 127 
$ exit 3.14159 -bash: exit: 3.14159: numeric argument required 
$ hexdump -n100000 /dev/urandom | tee &>/dev/null >(cat > file1.txt) >(cat > file2.txt) >(cat > file3.txt) >(cat > file4.txt) >(cat > file5.txt) $ find . -name '*.txt' -print0 | xargs -r0 cat | tee &>/dev/null >(head /dev/stdin > head.out) >(tail /dev/stdin > tail.out) xargs: cat: terminated by signal 13 $ echo $ 0 125 141 
$ sleep 5 && killall sleep & [1] 19891 $ sleep 100; echo $? Terminated: 15 143 
$ sh -c 'exit 3.14159'; echo $? sh: line 0: exit: 3.14159: numeric argument required 255 

According to the above table, exit codes 1 — 2, 126 — 165, and 255 have special meanings, and should therefore be avoided for user-specified exit parameters.

Please note that out of range exit values can result in unexpected exit codes (e.g. exit 3809 gives an exit code of 225, 3809 % 256 = 225).

Источник

Оцените статью
Adblock
detector