Hot answers tagged

32

moreutils' chronic command does just that: chronic mycommand will swallow mycommand's output, unless it fails, in which case the output is displayed.


21

As pointed out in comments, your quoting is wrong. You need single quotes to prevent $LINENO from being expanded when the trap line is first parsed. This works: #! /bin/bash err_report() { echo "Error on line $1" } trap 'err_report $LINENO' ERR echo hello | grep foo # This is line number 9 Running it: $ ./test.sh Error on line 9


17

The error codes aren't from make: make is reporting the return status of the command that failed. You need to look at the documentation of each command to know what each status value means. Most commands don't bother with distinctions other than 0 = success, anything else = failure. In each of your examples, ./dpp cannot be executed. When this happens, the ...


17

It's not really a question of ordering checks, simply the order in which the shell sets things up. Redirections are set up before the command is run; so in your example, the shell tries to open ~root/log for appending before trying to do anything involving ./write_file.py. Since the log file can't be opened, the redirection fails and the shell stops ...


14

Please advice how to force the chmod command to give exit code 0 in spite of error chmod -f 777 file.txt || : This would execute :, i.e. the null command, if chmod fails. Since the null command does nothing but always succeeds, you would see an exit code of 0.


12

I am not sure what shell sh.exe provides (since there are multiple shells that use that name for their Windows executables), but if it is bash or similar, you can use the $PIPESTATUS array. For your example, you would do: g++ -c source.cpp -o source.o 2>&1 | perl /bin/gSTLFilt.pl echo "${PIPESTATUS[0]}"


12

the ERR trap is not to run code when the shell itself exits with a non-zero error code, but when any command run by that shell that is not part of a condition (like in if cmd..., or cmd || ......) exits with a non-zero exit status (the same conditions as what causes set -e to exit the shell). If you want to run code upon exit of the shell with non-zero exit ...


12

Shells are built to do that sort of thing easily. if touch -r dcn_file "${dir_dcn}"/"${TAG1_dcn}".pcap then echo "Command ran successfully." else echo "Command had an error: $?" fi You will occasionally find some proprietary command that doesn't exit with 0 status on success and non-zero on failure, but thankfully, those abberations have almost ...


11

One common way is: die() { echo "$*" 1>&2 exit 1 } then you use it like this: mkdir -p some/path || die "mkdir failed with status $?" Or if you want it to include the exit status, you could change it to: die() { echo "FATAL ERROR: $* (status $?)" 1>&2 exit 1 } and then using it is a bit easier: mkdir -p some/path || ...


11

### do this bit once at the top of your script divert= exec 3<>"${divert:=$(mktmp)}" 4<>/dev/null rm -- "$divert"; unset divert ### then do this bit as often as needed command >&3 2>&3 cat <&3 >&"$(((RTN=$?)?2:4))" That should probably do the trick. It will buffer the output of each command into a deleted temporary ...


10

chmod -f 777 file.txt || true As it's an OR, if one of the statements returns true, then the the return is true. This results in an exit status of zero.


10

From the bash man page, section REDIRECTION (emphasis by me): Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. ... A failure to open or create a file causes the redirection to fail. So the shell tries to open the target file for stdout, which fails, and the command isn't ...


9

Bash has an option pipefail: The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit success- fully. So: set -o pipefail && $...


9

The bash variable $? hold the exit status of the last command run. For typical programs, the value 0 is success and any other value is failure. Specific return code should be documented in the man pages of the programs in question. You can use code like: touch -r dcn_file "${dir_dcn}"/"${TAG1_dcn}".pcap [ $? -ne 0 ]; then echo "Command failed: touch: $...


8

I think you want the trap function, specifically: error_func() { echo 'An error occurred!' exit 1 } trap error_func ERR Errors later will jump to the function. This is supported by at least bash, zsh, and ksh.


8

This is a broad ranging question and can probably only be answered with the same sorts of brushstrokes. Ultimately, it comes down to what you, the user, wish to protect. Fundamentally, you should not post anything that would allow someone else to find it easier to compromise your system, or any of the other connected tools or accounts you use. For this ...


8

Wrapping the whole into a function seems to do the trick: #!/bin/bash -e main () { readonly a=(1 2) # A syntax error is here: if (( "${a[#]}" == 2 )); then echo ok else echo not ok fi echo status $? echo 'Bad: has not aborted execution on syntax error!' } main "$@" Result: $ ./sh-on-syntax-err $ ./sh-on-syntax-...


7

You could rewrite your code like this: #!/bin/bash function try { "$@" code=$? if [ $code -ne 0 ] then echo "$1 did not work: exit status $code" exit 1 fi } try mkdir -p some/path try cd some/path try run_some_command If you don't actually need to log the error code, but just whether the command succeeded or not, you ...


7

Well, there are a couple of cases: This disk is part of a RAID array. Good. Just have md 'repair' the array like this: echo 'repair' > /sys/block/md0/md/sync_action. Problem solved without data loss. (I'm guessing this isn't the case for you, but you really ought to consider changing that.) You don't care about the data on the disk (or there isn't any). ...


7

It means that there are 22 sectors that could not be read. The next time you write to those sectors, if they can not be correctly written to, they will be remapped to a spare sector. You can use the badblocks utility to locate the bad sectors, and dd to write to them: sudo badblocks -b 512 /dev/sda For each sector listed, first verify that it can not be ...


7

Usually in case of error the command outputs messages to stderr so for you task you can just supress stdout mycommand > /dev/null


6

You can redirect the error output to a file and then retrieve that output: trap "rm -f /tmp/cfn-error.txt" 0 1 2 3 15 /opt/aws/bin/cfn-init -s ... 2>/tmp/cfn-error.txt || error_exit $(</tmp/cfn-error.txt) You should always clean up your mess, so don't forget to delete any temp files you create.


6

In traditional shells, the status of the first command in a pipeline is not reported at all to the script. Only the status of the last command is available, in $?. In bash ≥3.0, when you want to do is stop if an error occurs anywhere in the pipeline, use the pipefail option. g++ -c source.cpp -o source.o 2>&1 | perl /bin/gSTLFilt.pl More generally,...


6

It's because the return value of (( expression )) is not used for error indication. From the bash manpage: ((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to ...


5

There's a simpler way of what you're doing. If you use set -x, the script will automatically echo each line before it's executed. Also, ss soon as you execute another command, $? is replaced with the exit code of that command. You'll have to back it up to a variable if you're going to be doing anything with it other than a quick test-and-forget. The [ is ...


5

There are standard error values, defined in errno.h. You can look at this file on your system to see the numerical values. On most systems, they're in /usr/include/errno.h or a file that it includes. On Linux, most are in /usr/include/asm-generic/errno-base.h or /usr/include/asm-generic/errno.h, with a few more in /usr/include/bits/errno.h. If you have a ...


5

From the shell, you can run perror: $ perror 123 OS error code 123: No medium found That comes with MySQL. If you don't have MySQL, you can use Perl or Python, e.g.: $ perl -MPOSIX -e 'print strerror(123)' No medium found $ python -c 'import os; print os.strerror(123)' No medium found In a C program you can use the function with the same name: ...


5

If you really want to exit on an error and are using Bash, then you should also consider set -e. From help set: -e Exit immediately if a command exits with a non-zero status. This of course doesn't give you the flexibility of a did_it_work() function, but it is an easy way to make sure your bash script stops on an error without adding lots of calls ...


5

I'm assuming your cron email settings are all correct, and you otherwise get emails. Your sending all stdout to /dev/null, so anything that prints error messages must output them to stderr. You might want to make sure everything in the script is outputting correctly. At times I have had to work with third party code, which was sending everything to ...



Only top voted, non community-wiki answers of a minimum length are eligible