Can bash echo command return non-zero exit code?
Nope, no risk. From man bash
:
echo [-neE] [arg ...]
Output the args, separated by spaces, followed by a newline. The return status is always 0. If-n
is specified, the trailing newline is suppressed. If the-e
option is given, interpretation of the following backslash-escaped characters is enabled. The-E
option disables the interpretation of these escape characters, even on systems where they are interpreted by default. Thexpg_echo
shell option may be used to dynamically determine whether or notecho
expands these escape characters by default.echo
does not interpret--
to mean the end of options. echo interprets the following escape sequences:
Emphasis on "The return status is always 0".
From a code quality standpoint, I would recommend not using test
unless you're forced to for shell compatibility reasons. In general, use [[
, but for arithmetic expressions you can also use ((
:
# The generic way[[ $retry_counter -eq 0 ]] && echo "Thing didn't happen" && exit 1# The arithmetic way(( retry_counter == 0 )) && echo "Thing didn't happen" && exit 1
Yes, echo
has a non-zero return status if there's a write error.
Quoting the bash manual:
'echo'
echo [-neE] [ARG ...]
Output the ARGs, separated by spaces, terminated with a newline. The return status is 0 unless a write error occurs.
A demonstration:
$ cat foo.bash#!/bin/bashecho helloecho "The echo command returned a status of $?" > /dev/tty$ ./foo.bash > /dev/full./foo.bash: line 3: echo: write error: No space left on deviceThe echo command returned a status of 1$
/dev/full
is a device, similar to /dev/zero
except that any attempt to write to it will fail with an ENOSPC
error.