From ba1cc59cba0e9139e5a81b78ded95332cf6b063e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 8 Jan 2021 15:29:22 -0600 Subject: [PATCH] Add Provide A Fallback Value For Unset Parameter as a unix til --- README.md | 3 +- ...de-a-fallback-value-for-unset-parameter.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 unix/provide-a-fallback-value-for-unset-parameter.md diff --git a/README.md b/README.md index 3efdee4..875fae2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_999 TILs and counting..._ +_1000 TILs and counting..._ --- @@ -963,6 +963,7 @@ _999 TILs and counting..._ - [PID Of The Current Shell](unix/pid-of-the-current-shell.md) - [Print A Range Of Lines For A File With Bat](unix/print-a-range-of-lines-for-a-file-with-bat.md) - [Print Out Files In Reverse](unix/print-out-files-in-reverse.md) +- [Provide A Fallback Value For Unset Parameter](unix/provide-a-fallback-value-for-unset-parameter.md) - [Repeat Yourself](unix/repeat-yourself.md) - [Saying Yes](unix/saying-yes.md) - [Search Files Specific To A Language](unix/search-files-specific-to-a-language.md) diff --git a/unix/provide-a-fallback-value-for-unset-parameter.md b/unix/provide-a-fallback-value-for-unset-parameter.md new file mode 100644 index 0000000..41e5436 --- /dev/null +++ b/unix/provide-a-fallback-value-for-unset-parameter.md @@ -0,0 +1,29 @@ +# Provide A Fallback Value For Unset Parameter + +If you are using a value in a parameter expansion expression that isn't set, +the result will be empty. + +For instance, the XDG paths are not defined for me on OSX. + +```bash +$ echo "${XDG_CONFIG_HOME}" + +``` + +To make a script more robust, you can provide a fallback value (i.e. [default +value](https://wiki.bash-hackers.org/syntax/pe#use_a_default_value)). The +parameter expansion will use the fallback value if the primary value is either +unset or null. + +The syntax for this is to follow the primary parameter with `:-` and then the +fallback parameter. + +```bash +$ echo "${XDG_CONFIG_HOME:-$HOME/.local/share}" +/Users/jbranchaud/.local/share +``` + +Because I'm on OSX, this expands to my `$HOME` directory with `/.local/share` +appended. + +[source](https://unix.stackexchange.com/a/122848/5916)