0

I am writing a script under Unix system.

Is there any way to assign value like this:

x=($1 == "") ? 3 : 4

if $1 is empty we will assign value "3" to x, otherwise the value "4"

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
chipbk10
  • 5,783
  • 12
  • 49
  • 85
  • 2
    What you're looking for is called ternary operator, look here: http://stackoverflow.com/questions/3953645/ternary-operator-in-bash – Alberto Zaccagni Nov 12 '15 at 16:47
  • Specifically **ignore** the accepted answer and look at the [next answer](http://stackoverflow.com/a/12691027/258523). – Etan Reisner Nov 12 '15 at 16:51

1 Answers1

0

You can do it with either let or (()) bash constructions. For example:

a=1
let "b = a == 1 ? 2 : 3"
echo $b

For further details see man 1 bash

Andrey Starodubtsev
  • 5,139
  • 3
  • 32
  • 46
  • Please explain your code. Code only answers are not usually clear for others. – Jose Luis Nov 13 '15 at 08:22
  • Please clarify, what kind of comment do you expect? Author asks "how can i do this?", I sure can add explanatory line "You can do it with following construction:", but does it really increase clarity of the answer? – Andrey Starodubtsev Nov 13 '15 at 12:20
  • Well simply providing the answer without explaining why it works isn't enlightening for others nor does it encourage understanding. The answer may be clear but is it clear how the answer was found? It's like giving the answer to an equation without the whole process to get to it or at least some pointers. – Jose Luis Nov 13 '15 at 12:57