有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
还有两个答案
这里有一些思考的方法
Bash整数变量
此外,dutCh, Vladimir和ghostdog74的纠正答案,因为这个问题是关于整数和带标签的bash:
有这样的方法吗 Int a = (b == 5) ?C: d;
在bash下使用整数有一个很好的方法:
declare -i b=' RANDOM % 3 + 4 ' c=100 d=50 a=' b == 5 ? c : d '; echo $b '-->' $a
这个命令的输出行应该是:
4 --> 50
5 --> 100
6 --> 50
当然,声明整型变量只需要执行一次:
declare -i a b c d
c=100 d=50 b=RANDOM%3+4
a=' b == 5 ? c : d '
echo $a $b
100 5
b=12 a=b==5?c:d
echo $a $b
50 12
题外话:使用字符串作为数学函数:
mathString=' b == 5 ? c : d '
b=5 a=$mathString
echo $a $b
100 5
b=1 a=$mathString
echo $a $b
50 1
基于参数展开和间接
以下是Brad Parks和druid62的回答,这里有一种不局限于整数的方法:
c=50 d=100 ar=([5]=c)
read -p 'Enter B: ' b
e=${ar[b]:-d};echo ${!e}
如果b==5,那么ar[b]是c,间接做c是50。 否则ar[除5之外的任何值]为空,因此参数展开将默认为d,其中间接给出100。
同样的演示使用数组代替整数
ternArrayDemo(){
local -a c=(foo bar) d=(foo bar baz) e=(empty) ar=([5]=c [2]=d)
local b=${ar[$1]:-e}
b+=[@] # For array indirection
printf ' - %s\n' "${!b}"
}
Then
ternArrayDemo 0
- empty
ternArrayDemo 2
- foo
- bar
- baz
ternArrayDemo 4
- empty
ternArrayDemo 5
- foo
- bar
ternArrayDemo 6
- empty
或者使用关联数组
ternAssocArrayDemo(){
local -a c=(foo bar) d=(foo bar baz) e=(empty)
local -A ar=([foo]=c[@] [bar]=d[@] [baz]=d[-1])
local b=${ar[$1]:-e[@]}
printf ' - %s\n' "${!b}"
}
Then
ternAssocArrayDemo hello
- empty
ternAssocArrayDemo foo
- foo
- bar
ternAssocArrayDemo bar
- foo
- bar
- baz
ternAssocArrayDemo baz
- baz
其他回答
以下是一些选择:
在一行中使用if then else,这是可能的。
if [[ "$2" == "raiz" ]] || [[ "$2" == '.' ]]; then pasta=''; else pasta="$2"; fi
写一个这样的函数:
# Once upon a time, there was an 'iif' function in MS VB ...
function iif(){
# Echoes $2 if 1,banana,true,etc and $3 if false,null,0,''
case $1 in ''|false|FALSE|null|NULL|0) echo $3;;*) echo $2;;esac
}
像这样使用内部脚本
result=`iif "$expr" 'yes' 'no'`
# or even interpolating:
result=`iif "$expr" "positive" "negative, because $1 is not true"`
3-在案例回答的启发下,更灵活的一行用法是:
case "$expr" in ''|false|FALSE|null|NULL|0) echo "no...$expr";;*) echo "yep $expr";;esac
# Expression can be something like:
expr=`expr "$var1" '>' "$var2"`
这里有另一个选项,你只需要指定你分配一次的变量,不管你分配的是字符串还是数字:
VARIABLE=`[ test ] && echo VALUE_A || echo VALUE_B`
只是一个想法。:)
这样的方法怎么样:
# any your function
function check () {
echo 'checking...';
# Change the following to 'true' to emulate a successful execution.
# Note: You can replace check function with any function you wish.
# Be aware in linux false and true are funcitons themselves. see 'help false' for instance.
false;
}
# double check pattern
check && echo 'update' \
|| check || echo 'create';
看看条件语句是如何在RxJs中工作的(即过滤器管道)。 是的,从我的角度来看,这是代码复制,但更实用的方法。
(( a = b==5 ? c : d )) # string + numeric
[ $b == 5 ] && { a=$c; true; } || a=$d
这将避免在&&和||之间的代码失败时意外执行||之后的部分。