Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Bash substitutions in one statement?

Tags:

bash

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.

like image 404
Hubert Grzeskowiak Avatar asked Mar 27 '26 21:03

Hubert Grzeskowiak


1 Answers

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})
like image 167
iBug Avatar answered Mar 29 '26 09:03

iBug