4

I'd like to use a statement like this:

var=$(( func arg ? str1 : str2 ))

but bash gives this syntax error message:

syntax error in expression (error token is "arg")

I've played with various forms but I can't figure out how to make it accept a function with argument. Any ideas?

grok12
  • 3,526
  • 6
  • 26
  • 27

2 Answers2

2
echo $(( $(seq 1) + 1 ))
2

You need to use the same syntax as bash expects elsewhere. As far as the conditional ? iftrue : iffalse syntax, I don't think you can do that in bash. Instead, you can do something like:

echo $(( 1 + $(true && echo 1 || echo 0) ))
2
Steve Prentice
  • 23,230
  • 11
  • 54
  • 55
  • 1
    according to bash manual (section 6.5) the construction expr ? expr : expr is correct. – clt60 Jun 08 '11 at 18:41
  • I see. Thanks for the correction. So it works within the arithmetic evaluation, e.g. $(( 0 ? 1 : 2 )) results in 2. However, based on the original question, a syntax like var=$(func $([[ arg -eq "something"]] && str1 || str2)) might be more appropriate. – Steve Prentice Jun 08 '11 at 18:51
  • 2
    yes, the conditional operator **works only with arithmetic evaluation**. (and only with integers)... :) – clt60 Jun 08 '11 at 19:19
2

I think the correct answer is that there is no way to use the statement I asked about. The problem is that this conditional operator can only evaluate to an integer and not a string as I wanted to do.

jm666 answered the question in a comment to Steve's answer so I gave him an up vote.

grok12
  • 3,526
  • 6
  • 26
  • 27