Reputation: 16516
In Bash you can substitute an empty or undefined variable with this:
${myvar:-replacement}
You can also replace substrings in variables like this:
${myvar//replace this/by this}
Now I want to combine both substitutions into one: If variable is undefined, set it to replacement
, otherwise replace a part of it with something else.
I can write this in two lines without problems.
myvar=${myvar:-replacement}
myvar=${myvar//replace this/by this}
or to more closely reflect my business logic:
if [[ -n "${myvar:-}" ]]; then
myvar="${myvar//replace this/by this}"
else
myvar="replacement"
fi
Is there a way to combine both substitutions into one statement / one line?
I have tried this without success:
myvar=${${myvar:-replacement}//replace this/by this} # bad substitution
I am using set -u
in my scripts so that they error out when I use undefined variables. That's why I need the first sub on undefined var.
Upvotes: 3
Views: 246
Reputation: 37297
As far as I know this is not possible in Bash.
The best thing you could do is writing them on multiple lines, or use an NOP command, or use utilities:
myvar=${myvar:-replacement}
myvar=${myvar/src/dest}
myvar=$(sed 's/src/dest/g' <<< ${myvar:-defaulttext})
Upvotes: 3