Bash – Provide default value if command returns with non-zero exit code

bashcatexit-statusshell

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

Best Answer

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.