Shell Scripting Ternary operator to get string result

In shell scripts, I use the ternary operator as follows:

(( numVar == numVal ? (resVar=1) : (resVar=0) ))

I watched a shell script tutorial from Derek Banas and got the above syntax at 41:00 video

https://www.youtube.com/watch?v=hwrnmQumtPw&t=73s

The above code works when we assign numbers resVar, but if I try to assign a string resVar, it always returns 0.

(( numVar == numVal ? (resVar="Yop") : (resVar="Nop") ))

and also tried

resVar=$(( numVar == numVal ? (echo "Yop") : (echo "Nop") ))

So what is the right way to do this?

+4
source share
3 answers

, , bash - . bash man bash ARITHMETIC EVALUATION:

, (. let and declare builtin commands ). , 0 . , , C. . .
(...)

:

, resVar 0 "Yop" "Nop" , bash 0. man bash :

null 0.

, :

:

((result = condition? value_if_true: value_if_false))

, , :

result = $([ "$ a" == "$ b" ] & & amcho; echo "value_if_true" || echo "__" )

( "$ a" == "$ b" , [, can .)

+3

, bash, . , :

$ arr=(Nop Yop)
$ declare -p arr
declare -a arr='([0]="Nop" [1]="Yop")'
$ numVar=5; numVal=5; resvar="${arr[$((numVar == numVal ? 1 : 0))]}"; echo "$resvar"
Yop
$ numVar=2; numVal=5; resvar="${arr[$((numVar == numVal ? 1 : 0))]}"; echo "$resvar"
Nop

, , 0 1 , ; :

$ resvar="${arr[$((numVar==numVal))]}"
+1

you can use this simple expression:

resVar=$([ numVar == numVal  ] && echo "Yop" || echo "Nop")
0
source

Source: https://habr.com/ru/post/1691562/


All Articles