Provide default value if command returns with non-zero exit code
6,801
Solution 1
Your construct is fine. You could even do someting like
cat config || cat defaultconfig
If you use some random command (like the ./get_config_from_web
in comments), you'll have to make sure the command does give a sensible return status. That can be tricky, shell scripts just return the result of the last command executed, you'd have to do a exit
if you want something else as result.
Solution 2
The following will echo 42 for any noncaught error condition:
trap "echo 42" ERR
You can make this a configurable variable:
trap 'echo "${CONFIG:=42}"' ERR # if $CONFIG is not set, it will be defaulted to 42
Related videos on Youtube
Author by
Cory Klein
Updated on September 18, 2022Comments
-
Cory Klein over 1 year
I have some configuration in file
config
and would like tocat
that file. However, sometimesconfig
doesn't exist. In this case, I would like to have my command output a default value.Perhaps something that worked like this:
$ ls $ cat config || echo 42 42 $ echo 73 > config $ cat config || echo 42 73
-
Cory Klein over 8 yearsThis appears to work for the
cat config
example, but I was hoping for a solution that works regardless of whether the failure is due to a missing file. For example./get_config_from_web.sh || echo 42
. -
MelBurslan over 8 yearsdoes it have to be a one-liner ?
-
MelBurslan over 8 yearsI personally have not seen anything other than
||
and&&
constructs to determine the success or failure of an action in the same command space. But again with the enhancements in shell and me being an old timer, it might entirely be possible in a nook and cranny that eludes me and probably you as well -
Pankaj Goyal over 8 yearsPresuming of course that
defaultconfig
is guaranteed to exist. -
Cory Klein over 8 yearsThe critical problem here is that it's the output of the commands that I care about.
cat config
gives an errorcat: config: No such file or directory
ifconfig
doesn't exist. So I end up getting the output of both commands instead of just the second one. -
Cory Klein over 8 yearsI'm not quite sure I understand how the
trap
logic would be combined with thecat config
command from the example. Can you elaborate? -
Cory Klein over 8 yearsAh! I could pipe stderr to
/dev/null
and it works:cat config 2> /dev/null || echo 42
. -
Jeff Schaller over 8 years
$cat config
-> "cat: config: No such file or directory\n" (from cat's error) "42" (from the trap's echo)