-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)

4
  • 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. Commented Oct 9, 2022 at 23:03
  • 1
    @wjandrea example given Commented Oct 9, 2022 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. Commented Oct 9, 2022 at 23:14
  • BTW, set -e is generally regarded in the bash community as a bad idea. See BashFAQ #105 describing the pitfalls with set -e, and 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 is widely integrated into, or available via a plugin for, many editors now) in place of set -u. Commented Oct 9, 2022 at 23:19

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.