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.

1
  • That's actually C++ code Commented Oct 9, 2015 at 14:35

1 Answer 1

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

3 Comments

Hmmm, makes sense, although not very readable. honestly I'm tempted to do it with if then else statements.
Well that looks a lot nicer. Is there a reference for that :- construct?
In the link I provided in the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.