-3

It is not hard to set a default variable in bash. E.g: How to write a bash script that takes optional input arguments?

But, these methods fail when using set -euxo pipefail. What methods are compatible with the -u flag?

Example:

set -euxo pipefail

foo=${2:test}
echo $foo

for Bash GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Please give an example. I just tried `echo "${1:-foo}"` and it worked fine. What version of Bash are you using? I think I read that this behaviour can vary across versions. I'm using 5.0. – wjandrea Oct 09 '22 at 23:03
  • 1
    @wjandrea example given – Foobar Oct 09 '22 at 23:05
  • 1
    It has to be colon-hyphen `:-` or hyphen `-`. A colon by itself `:` selects a substring, e.g. with `set -- hello world; test=2`, the result would be `rld`. – wjandrea Oct 09 '22 at 23:14
  • BTW, `set -e` is generally regarded in the bash community as a bad idea. See [BashFAQ #105](https://mywiki.wooledge.org/BashFAQ/105#Exercises) describing the pitfalls with `set -e`, and [BashFAQ #112](https://mywiki.wooledge.org/BashFAQ/112) describing best practices for working with `set -u`. I _strongly_ advise explicit error handling in place of `set -e`, and more weakly advise static checking ([shellcheck](http://shellcheck.net/) is widely integrated into, or available via a plugin for, many editors now) in place of `set -u`. – Charles Duffy Oct 09 '22 at 23:19

1 Answers1

0

The accepted answer to the linked duplicate works fine -- you're just misreading it.

It suggests:

somecommand ${1:-foo} # GOOD

...or...

somecommand ${1-foo} # GOOD

...not...

somecommand ${1:foo} # BAD
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441