Unix & Linux Stack Exchange
Q&A for users of Linux, FreeBSD and other Unix-like operating systems
Latest Questions
1
votes
1
answers
104
views
If fprinting to stderr fails, which error code should a C program return?
Assume the following C snippet showing a piece of error handling: ```C #include #include … int main(int argc, char argv*[]) { int retval=0; … if(3!=argc) { /* wrong number of arguments */ retval |= EX_USAGE; const int fprintf_retval = fprintf(stderr, "Bad syntax.\n"); if (0>=fprintf_retval) retval |...
Assume the following C snippet showing a piece of error handling:
#include
#include
…
int main(int argc, char argv*[]) {
int retval=0;
…
if(3!=argc) { /* wrong number of arguments */
retval |= EX_USAGE;
const int fprintf_retval = fprintf(stderr, "Bad syntax.\n");
if (0>=fprintf_retval) retval |= … Hmm … ;
}
…
return retval;
}
Which error constant from sysexits.h should be placed instead of “… Hmm …”? We can say EX_OSERR (a failure to print an error message shows that something is off, though not necessarily deep in the operating system), or EX_IOERR (it's an output error, though not necessarily into a file), or EX_SOFTWARE (fairly general, but the reason for a failure to print an error typically lies outside the C program, and the error might relate to the operating system). Based only on the comments in sysexits.h, neither of the three constants fits perfectly. So what's the convention?
EDIT: In the scope of this question, we assume that the programmer does want to discern between certain kinds of errors via the exit code, and that more than one error can occur.
user743115
(1 rep)
Jul 24, 2025, 12:48 AM
• Last activity: Jul 24, 2025, 09:15 AM
5
votes
3
answers
2500
views
In bash, how to capture stdout and the exit code of a command when the -e flag is active?
To capture stdout and the exit code when the `-e` flag (exit the shell immediately when a command fails) is not set, I would use ``` OUTPUT="$(my_command)" exit_code=$? ``` To capture the exit code with `-e` set, I would use ``` exit_code=0 my_command || exit_code=$? ``` But combining the two approa...
To capture stdout and the exit code when the
-e
flag (exit the shell immediately when a command fails) is not set, I would use
OUTPUT="$(my_command)"
exit_code=$?
To capture the exit code with -e
set, I would use
exit_code=0
my_command || exit_code=$?
But combining the two approaches doesn't work:
exit_code=0
OUTPUT="$(my_command || exit_code=$?)"
This doesn't set exit_code
, because it is assigned in a subshell and the copy in the parent shell is not updated.
So, how do I capture stdout and the exit code? I could unset -e
or e.g. write the exit code to a tempfile, but I would like something simpler.
JanKanis
(1421 rep)
Nov 4, 2024, 11:07 AM
• Last activity: Jun 17, 2025, 12:20 PM
0
votes
1
answers
70
views
Understanding `bash` options -Ee
In a larger script I have ```bash trap -p echo "settings: [$-], command: [$*]" "$@" echo "return code $?" ``` and I get the output ``` trap -- '_shunit_cleanup EXIT' EXIT trap -- '_shunit_cleanup INT' SIGINT trap -- '_shunit_cleanup TERM' SIGTERM settings: [ehuBET], command: [false VAR2 VAR1] return...
In a larger script I have
trap -p
echo "settings: [$-], command: [$*]"
"$@"
echo "return code $?"
and I get the output
trap -- '_shunit_cleanup EXIT' EXIT
trap -- '_shunit_cleanup INT' SIGINT
trap -- '_shunit_cleanup TERM' SIGTERM
settings: [ehuBET], command: [false VAR2 VAR1]
return code 1
We see that the command false
is run and we see that it exits with code 1
. But we also have set -e
from which I would expect that we should never see the line return code 1
, because as soon as false
exists with 1
the whole script should stop. Afaict the traps are not relevant.
I tried to reproduce the situation with a minimal example, but in all smaller tests, the immediate exit due to -e
does happen.
Which setting or options should I look at to explain the above?
**More background and findings:**
The problematic code is called as part of a shunit2
test from within a testing function. If I call that same testing function directly, without invoking it through shunit2
, the problem is gone.
But to confirm: my confusion lies mostly in the facts which can be seen from the output above alone: set -e
seems to be on, false
is called but instead of exiting right away, the next line of code (echo
) is executed anyway.
Harald
(1030 rep)
Apr 27, 2025, 07:22 AM
• Last activity: Jun 12, 2025, 02:44 PM
4
votes
2
answers
2395
views
How to print the failed command that caused the script's failure?
I'm using the `-e` flag. Usage: #!/bin/bash -e Explained: -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status When a command in the script fails, the script exits and doesn't continue to execute the rest of the commands, which is exactly what I want. But, t...
I'm using the
-e
flag.
Usage:
#!/bin/bash -e
Explained:
-e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status
When a command in the script fails, the script exits and doesn't continue to execute the rest of the commands, which is exactly what I want.
But, the failure contains just the info that the failed command chooses to disclose.
Sometimes the failed command is very complicated, like a curl with many headers.
**How do I print the failed command? I mean, immediately after it failed.**
I know I can use the -x
bash flag but it will print all of the executed commands. I'd like to see just the failed one.
AlikElzin-kilaka
(571 rep)
Jan 23, 2023, 02:43 PM
• Last activity: May 22, 2025, 05:07 PM
1
votes
1
answers
848
views
What does it mean when Duplicity exits with exit status 23?
I'm running Duplicity for backup of my desktop to a remote storage. Everything has been working fine, but now I see in my log that Duplicity has been exiting with exit status 23 for a couple of runs. As of what I can see the backups are running and the backups are uploaded to the remote computer. Th...
I'm running Duplicity for backup of my desktop to a remote storage. Everything has been working fine, but now I see in my log that Duplicity has been exiting with exit status 23 for a couple of runs. As of what I can see the backups are running and the backups are uploaded to the remote computer.
The exit status 23 seems to only happen when it's run in the background as a cron-job. When I run the backup script manually I get a 0 exit status.
Duplicity's man page lacks info on the meanings of the programs exit statuses, so I don't really know where to start.
cat syslog.1
outputs:
...
Jan 23 12:54:35 xx anacron: Job `cron.daily' started
Jan 23 12:54:35 xx anacron: Updated timestamp for job `cron.daily' to 2019-01-23
Jan 23 12:54:45 xx kernel: [ 322.467223] EXT4-fs (sdb1): warning: maximal mount count reached, running e2fsck is recommended
Jan 23 12:54:45 xx kernel: [ 322.473997] EXT4-fs (sdb1): recovery complete
Jan 23 12:54:45 xx kernel: [ 322.474404] EXT4-fs (sdb1): mounted filesystem with ordered data mode. Opts: (null)
Jan 23 12:55:03 xx kernel: [ 340.754000] EXT4-fs (sdc): recovery complete
Jan 23 12:55:03 xx kernel: [ 340.794089] EXT4-fs (sdc): mounted filesystem with ordered data mode. Opts: (null)
...
PetaspeedBeaver
(1398 rep)
Jan 21, 2019, 07:59 PM
• Last activity: Mar 28, 2025, 09:50 AM
1
votes
1
answers
119
views
unzip returns exit code 1 on empty archive
I have an valid, yet empty zip archive: ``` $ file 22.zip 22.zip: Zip archive data (empty) $ xxd 22.zip 00000000: 504b 0506 0000 0000 0000 0000 0000 0000 PK.............. 00000010: 0000 0000 0000 ``` Trying to list the archive content or unzipping the file gives both a warning and returns exit code...
I have an valid, yet empty zip archive:
$ file 22.zip
22.zip: Zip archive data (empty)
$ xxd 22.zip
00000000: 504b 0506 0000 0000 0000 0000 0000 0000 PK..............
00000010: 0000 0000 0000
Trying to list the archive content or unzipping the file gives both a warning and returns exit code 1.
$ unzip -l 22.zip; echo $?
Archive: 22.zip
warning [22.zip]: zipfile is empty
1
$ unzip 22.zip; echo $?
Archive: 22.zip
warning [22.zip]: zipfile is empty
1
I understand the warning, but the exit code seems wrong. There is nothing wrong with an empty file; for example running cat
on an empty file yields exit code 0.
What is the reasoning behind unzip
returning an exit code 1 on a valid, yet empty file?
miku
(683 rep)
Mar 13, 2025, 10:26 AM
• Last activity: Mar 13, 2025, 10:35 AM
1
votes
1
answers
2791
views
How do I exit with a failure code if the wrong number of args are passed to my script?
I'm using bash. How can I exit with a non-success code if my script has the wrong number of arguments? I have this #!/bin/bash if [ "$#" -ne 3 ]; then echo "Should be three parameters to this script -- [CWD driver-directory side-file]" fi but then the script continues.
I'm using bash. How can I exit with a non-success code if my script has the wrong number of arguments?
I have this
#!/bin/bash
if [ "$#" -ne 3 ]; then
echo "Should be three parameters to this script -- [CWD driver-directory side-file]"
fi
but then the script continues.
Dave
(2808 rep)
Jul 25, 2019, 02:18 PM
• Last activity: Mar 5, 2025, 12:00 AM
11
votes
3
answers
4749
views
How to run multiple processes and exit if any of them exits or fails
I am running multiple processes and want to exit with the appropriate exit code (this means error on failure, success otherwise) if any of them fails or exists. Additionally if any child process exits or fails, any other child processes should also be shut down. My current non-functional solution (y...
I am running multiple processes and want to exit with the appropriate exit code (this means error on failure, success otherwise) if any of them fails or exists.
Additionally if any child process exits or fails, any other child processes should also be shut down.
My current non-functional solution (yarn is just an example; may be any other command):
#!/bin/bash -e
# Run other process before start
sh ./bin/optimize.sh
trap 'exit' INT TERM
trap 'kill -INT 0' EXIT
# Run Schedule
sh ./bin/schedule.sh &
# Run a long running task
yarn task &
wait
./bin/schedule.sh
:
#!/bin/bash -e
while true; do
yarn schedule
sleep 30
done
If something in yarn schedule
fails, everything exists correctly. But when I kill the process via ctrl+c or yarn task
exits yarn schedule
keeps running.
How to get this working regardless of what the child processes are (bash, yarn, php or whatever)?
I can't use GNU parallel.
Olivenbaum
(211 rep)
Dec 10, 2018, 07:28 PM
• Last activity: Nov 12, 2024, 02:08 PM
8
votes
1
answers
1473
views
How to tell systemd to start a service after a clean exit of another service
I'm trying to start a systemd. service after another service exits properly (e.g : in a application it could be ```exit(EXIT_SUCCESS)``` ). I've seen that there might be an **OnSuccess** option in the later release of systemd, but I would like to be able to do it without that option since my version...
I'm trying to start a systemd. service after another service exits properly (e.g : in a application it could be
(EXIT_SUCCESS)
).
I've seen that there might be an **OnSuccess** option in the later release of systemd, but I would like to be able to do it without that option since my version of systemd doesn't support it.
Is it possible to do such thing properly?
oneshepherdssheep
(81 rep)
Oct 26, 2021, 01:28 PM
• Last activity: Oct 28, 2024, 04:02 PM
1
votes
2
answers
108
views
Need to identify executable files via boolean shell test construct
I am trying to symlink executable files to a `bin` directory within a docker script. I need a way to identify executables and return boolean status. I've been trying this: ```lang-sh for i in ../src/u-boot/tools/*; do if ! [[ "readelf -h $i | grep -q DYN" ]]; then ln -s $i .; fi; done ``` It doesn't...
I am trying to symlink executable files to a
bin
directory within a docker script. I need a way to identify executables and return boolean status. I've been trying this:
-sh
for i in ../src/u-boot/tools/*; do if ! [[ "readelf -h $i | grep -q DYN" ]]; then ln -s $i .; fi; done
It doesn't work and I do not understand why.
If I look at the actual return values I see the values I expect:
-shellsession
root@0f1bca692c90:/home/work/bin# readelf -h ../src/u-boot/tools/mkimage |grep -q DYN
root@0f1bca692c90:/home/work/bin# echo $?
0
root@0f1bca692c90:/home/work/bin# readelf -h ../src/u-boot/tools/mkimage.c |grep -q DYN
readelf: Error: Not an ELF file - it has the wrong magic bytes at the start
root@0f1bca692c90:/home/work/bin# echo $?
1
I'm assuming that I misunderstand how Bash interprets return values. I've tried with single and double brackets, and I get the same behavior.
**Update**
I was able to get it working like this:
-sh
RUN for i in ../src/u-boot/tools/*; do if /usr/bin/readelf -h $i | grep -q DYN; then ln -s $i .; fi; done
mreff555
(131 rep)
Oct 24, 2024, 02:21 PM
• Last activity: Oct 27, 2024, 11:16 AM
0
votes
1
answers
77
views
Why does a program named sl (stream locomotive) always end with an exit status of "1"?
Why does a program named sl (stream locomotive) always end with an exit status of "1"? ```sh sl ``` Animation sl now running... ``` $ echo $? 1 ``` Why not zero exit status? Can I get an explanation? I am running it in `tmux`.
Why does a program named sl (stream locomotive) always end with an exit status of "1"?
sl
Animation sl now running...
$ echo $?
1
Why not zero exit status?
Can I get an explanation? I am running it in tmux
.
popcorn games
(3 rep)
Sep 25, 2024, 06:03 PM
• Last activity: Sep 25, 2024, 07:05 PM
24
votes
7
answers
66981
views
How does one extract a command's exit status into a variable?
I started learning Bash a couple of days ago. I'm trying to obtain an exit status of `grep` expression into a variable like this: check=grep -ci 'text' file.sh and the output that I got is No command '-ic' found Should I do it with a pipe command?
I started learning Bash a couple of days ago.
I'm trying to obtain an exit status of
grep
expression into a variable like this:
check=grep -ci 'text' file.sh
and the output that I got is
No command '-ic' found
Should I do it with a pipe command?
omri gilhar
(343 rep)
Jul 7, 2016, 08:07 AM
• Last activity: Sep 9, 2024, 10:49 AM
2
votes
2
answers
291
views
How to capture exit code of subshell (while in pipe)
`somefile` contains this: aaa bbb ccc This is the subshell which can exit before completing all iterations. In my particular case is `while` but it could be `for` or `until`: ``` cat "somefile" | while read -r line do echo "$line" if [ "$line" = "bbb" ] then exit 2 fi done exit_code="$?" if [ "$exit...
somefile
contains this:
aaa
bbb
ccc
This is the subshell which can exit before completing all iterations. In my particular case is while
but it could be for
or until
:
cat "somefile" | while read -r line
do
echo "$line"
if [ "$line" = "bbb" ]
then
exit 2
fi
done
exit_code="$?"
if [ "$exit_code" -ne 0 ]
then
exit
fi
echo "I'm here"
The issue is that the last line I'm here
is printed. My intention is to exit completely to terminal. However I'm not sure if that's correct and will works with all shells. Is that even POSIX? Any mention about how this has to work in POSIX?
I've asked several AI engines and each one comes with a different answer:
1. Copilot: says that the exit_code will be always 0, because that's the exit code of cat. Could be any other command.
2. ChatGPT: says the exit_code will the the number after exit, like here 2, because it propagates.
3. Gemini: says the exit_code will be always 0, because $? gets the exit code of the last instruction, which is done
and is always 0.
Any help here? I've tried in bash and it detects the exit code, but not sure if that's some specific bash configuration (like pipefail or or it's the way it works with any shell (for example in UNIX as well).
Smeterlink
(295 rep)
Aug 21, 2024, 06:21 AM
• Last activity: Aug 21, 2024, 08:03 AM
3
votes
2
answers
7988
views
best range for custom exit code in linux?
Here I am developing an application that can exit for various custom reasons. What is the best range for a custom exit code (like 150-200)? I know this opinion-based but still i wanted to know the different perspective of multiple users. Kindly share your opinions, Thanks.
Here I am developing an application that can exit for various custom reasons. What is the best range for a custom exit code (like 150-200)?
I know this opinion-based but still i wanted to know the different perspective of multiple users.
Kindly share your opinions, Thanks.
Karthik Nedunchezhiyan
(825 rep)
Aug 13, 2020, 05:30 AM
• Last activity: Aug 5, 2024, 09:31 AM
0
votes
1
answers
87
views
Evaluating exit code of pipe or fifo
So i have something along the lines of: set -eo pipefail ssh localhost "ls; exit 1" | cat > output I thought pipefail would prevent cat to write to ouput (because of the exit code from ssh session), but it seems it will not. I then tried creating a fifo, but i am unsure of how to read the exit statu...
So i have something along the lines of:
set -eo pipefail
ssh localhost "ls; exit 1" | cat > output
I thought pipefail would prevent cat to write to ouput (because of the exit code from ssh session), but it seems it will not. I then tried creating a fifo, but i am unsure of how to read the exit status of ssh without consuming the content in the fifo, because it seems it will wait until something "consumes" it.
set -eo pipefail
[[ -e /tmp/sshdump ]] && rm /tmp/sshdump; mkfifo /tmp/sshdump;
ssh localhost "ls; exit 1" > /tmp/sshdump &
wait $! && cat > output
So, how do i:
1. avoid make the pipe exit early in the first example (and not reach cat)?
2. checking exit code of ssh without consuming the fifo content?
if it matters, a POSIX compatible solution is always appreciated, but bash is fine too. In my particular case i'm using windows and git-bash, so maybe there is som quirks i'm not aware of.
EDIT: full disclosure, i should probably have explained what i was traying to achieve with this from the get go, rather than simplifying it to the point where the question doesn't properly reflect the intent. I was trying to pipe the output of "mysqldump" on a remote ssh shell directly to "wp db import" on my machine without creating intermediate files. I originally thought pipefail would stop the pipeline and thus prevent the import on my end to go through if there was a failure. Why this was desireable to me was simplicity of not creating temporary files, and of course less code.
PKSWE
(103 rep)
Aug 1, 2024, 09:28 PM
• Last activity: Aug 2, 2024, 10:52 AM
68
votes
3
answers
252864
views
Exit code at the end of a bash script
I am confused about the meaning of the exit code in the end of a bash script: I know that exit code 0 means that it finished successfully, and that there are many more exit codes numbers (127 if I'm not mistaken?) My question is about when seeing exit code 0 at the end of a script, does it force the...
I am confused about the meaning of the exit code in the end of a bash script:
I know that exit code 0 means that it finished successfully, and that there are many more exit codes numbers (127 if I'm not mistaken?)
My question is about when seeing exit code 0 at the end of a script, does it force the exit code as 0 even if the script failed or does it have another meaning?
soBusted
(941 rep)
Sep 6, 2016, 02:20 PM
• Last activity: Jun 29, 2024, 11:38 AM
1
votes
2
answers
1396
views
Get exit status of the first command in a pipeline *in the second command*
My question is similar to , but I want to get the exit status of the first command in the pipe *within* the pipe. Here's an example: ``` false | echo "$?" ``` returns `0` rather than the intended `1`. `PIPESTATUS` gives the previous error code out: ``` false | echo "$PIPESTATUS" ``` returns `0` the...
My question is similar to , but I want to get the exit status of the first command in the pipe *within* the pipe.
Here's an example:
false | echo "$?"
returns 0
rather than the intended 1
.
PIPESTATUS
gives the previous error code out:
false | echo "$PIPESTATUS"
returns 0
the first time and then 1
, giving the result after the operation itself. My intent with this is to make a function like this:
debug() {
# Eventually will be formatted as JSON
echo "$(cat) was the result and the error code was $?"
}
(
echo "Foo"
false # To simulate an error
) | debug # debug should output "Foo was the result and the error code was 1"
MilkyDeveloper
(113 rep)
Apr 24, 2023, 10:47 PM
• Last activity: May 10, 2024, 08:56 PM
2
votes
2
answers
1694
views
What does it mean 'exit 1' for a job status after rclone sync
I am copying some large datasets to google drive using rclone in Linux on MobaXterm. First, I copy the dataset using; -cpu:~$ nohup rclone copy /path_to_source/. /path_to_destination & once copying is completed, I use sync to make sure everything is copied using; -cpu:~$ nohup rclone sync /path_to_s...
I am copying some large datasets to google drive using rclone in Linux on MobaXterm. First, I copy the dataset using;
-cpu:~$ nohup rclone copy /path_to_source/. /path_to_destination &
once copying is completed, I use sync to make sure everything is copied using;
-cpu:~$ nohup rclone sync /path_to_source/. /path_to_destination &
Now when check the job status using;
ps -ef | grep rclone
For one of the jobs, it gives;
+ Exit 1 nohup rclone sync /path_to_source/. /path_to_destination &
I was expecting to see 'Done' instead of 'Exit 1'. What does this mean? Does it mean sync is unsuccessful? If so what would be the reason?
kutlus
(375 rep)
Apr 1, 2019, 07:32 PM
• Last activity: Mar 12, 2024, 10:55 PM
1
votes
2
answers
77
views
Ensuring Distinguishable Exit Codes for Shell Scripts
Say I have two shell scripts, `a.sh` and `b.sh`, where `a.sh` calls `b.sh` somewhere inside. Then, say that `b.sh` could exit with exit codes `0`, `1`, or `2`. What are some techniques that can be employed to ensure that the exit codes of `a.sh` are distinguishable from the exit codes of `b.sh` ? Fo...
Say I have two shell scripts,
a.sh
and b.sh
, where a.sh
calls b.sh
somewhere inside. Then, say that b.sh
could exit with exit codes 0
, 1
, or 2
.
What are some techniques that can be employed to ensure that the exit codes of a.sh
are distinguishable from the exit codes of b.sh
? For example, if we decide that a.sh
could exit with exit code 1
, then that is ambiguous to the caller -- did a.sh
fail, or did b.sh
fail ? So that means that a.sh
shouldn't use exit codes 1
or 2
. But there are only a limited number of exit codes to pick from, and b.sh
may theoretically add any number of additional exit codes as it evolves.
Are there techniques that can be employed to pass along some bit of extra data with an exit code to ensure that we, as script users, are able to differentiate between _which_ program actually failed ? Or as script authors, are we meant to assume that our scripts will be treated as a black box, and that our users aren't meant to have any insight into the individual operations that the script we're running is performing ? In other words is the exit code of a shell script meant to only ever be interpreted as the result of the outermost script ?
Pacopenguin
(113 rep)
Feb 13, 2024, 06:56 PM
• Last activity: Feb 14, 2024, 11:37 AM
2
votes
1
answers
148
views
Detect if the previous line was a command or not
I'd like to enable [Windows terminal shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/shell-integration) in bash. (Don't judge me.) One nice feature is that the terminal can show a mark in the scrollbar for each command, with a color depending on whether the command ex...
I'd like to enable [Windows terminal shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/shell-integration) in bash. (Don't judge me.) One nice feature is that the terminal can show a mark in the scrollbar for each command, with a color depending on whether the command executed was successful or not. However, if no command is executed (empty line, Ctrl-C...) then the color should remain neutral.
This is achieved by putting special escape sequences in the prompt. A simplified version of my current prompt is the following:
PS1="\[\e]133;D;\$?\a\] \$ \[\e]133;B\a\]"
There, \e]133;D;\$?\a
marks the end of the previous command, and the ;\$?
includes the last return code to let the terminal know how it ended. (And \e]133;B\a
marks the end of the prompt.) I'd like to *not* include the ;\$?
if the previous input was not a command (again: blank line, Ctrl-C...).
Is there a way to detect this situation?
The documentation linked above provides a solution for PowerShell, but I don't see how to apply it to bash. PowerShell keeps a unique id for each history entry, and before each prompt is displayed, a little bit of logic updates a global variable with it. On the other hand, as far as I know, bash doesn't keep such ids.
If you have a solution for zsh, I'll also take it.
N. I.
(230 rep)
Feb 2, 2024, 08:22 AM
• Last activity: Feb 2, 2024, 12:48 PM
Showing page 1 of 20 total questions