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
Share:
6,801

Related videos on Youtube

Cory Klein
Author by

Cory Klein

Updated on September 18, 2022

Comments

  • Cory Klein
    Cory Klein over 1 year

    I have some configuration in file config and would like to cat that file. However, sometimes config 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
    Cory Klein over 8 years
    This 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
    MelBurslan over 8 years
    does it have to be a one-liner ?
  • MelBurslan
    MelBurslan over 8 years
    I 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
    Pankaj Goyal over 8 years
    Presuming of course that defaultconfig is guaranteed to exist.
  • Cory Klein
    Cory Klein over 8 years
    The critical problem here is that it's the output of the commands that I care about. cat config gives an error cat: config: No such file or directory if config doesn't exist. So I end up getting the output of both commands instead of just the second one.
  • Cory Klein
    Cory Klein over 8 years
    I'm not quite sure I understand how the trap logic would be combined with the cat config command from the example. Can you elaborate?
  • Cory Klein
    Cory Klein over 8 years
    Ah! I could pipe stderr to /dev/null and it works: cat config 2> /dev/null || echo 42.
  • Jeff Schaller
    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)