0

I found this question for how to do conditional assignment in bash, but what I'm trying to do is a little more complex, and I can't seem to get the syntax right. The condition in my case is to test a variable to see if it exists, and the output is concatenated to a string.

Here's what I have so far:

fwversion="${BASH_REMATCH[1]}.$(( [[ BASH_REMATCH[2] ]] ? BASH_REMATCH[2] : 0 ))"

Which produces this error message:

bash: line 41: [[ BASH_REMATCH[2] ]] ? BASH_REMATCH[2] : 0 : syntax error: 
operand expected (error token is "[[ BASH_REMATCH[2] ]] ? BASH_REMATCH[2] : 0 ")

Here's what I'm trying to achieve as C++ code:

std::string fwversion = BASH_REMATCH[1] + "." + ((BASH_REMATCH[2]) ? : BASH_REMATCH[2] : 0);

What's the correct syntax to do this in bash? Thanks.

Community
  • 1
  • 1
Sonic Atom
  • 436
  • 5
  • 15

1 Answers1

1

Looks like [[ ... ]] are not understood in an arithmetic expression.

I'd do this:

fwversion=${BASH_REMATCH[1]}
[[ ${BASH_REMATCH[2]} ]] && fwversion+=${BASH_REMATCH[2]} || fwversion+=0

or

[[ ${BASH_REMATCH[2]} ]] && ext=${BASH_REMATCH[2]} || ext=0
fwversion="${BASH_REMATCH[1]}.$ext"

On second thought, I wouldn't do that at all, I'd use the power of the shell's parameter expansion

str="foo:bar"
if [[ $str =~ ^([a-z]+):([a-z]*)$ ]]; then
    echo "${BASH_REMATCH[1]}.${BASH_REMATCH[2]:-0}"
fi
foo.bar
str="foo:"
if [[ $str =~ ^([a-z]+):([a-z]*)$ ]]; then
    echo "${BASH_REMATCH[1]}.${BASH_REMATCH[2]:-0}"
fi
foo.0
glenn jackman
  • 238,783
  • 38
  • 220
  • 352