有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
有这样的方法吗
int a = (b == 5) ? c : d;
使用Bash ?
当前回答
代码:
a=$([ "$b" == 5 ] && echo "$c" || echo "$d")
其他回答
回答:int a = (b == 5) ?C: d;
只写:
b=5
c=1
d=2
let a="(b==5)?c:d"
echo $a # 1
b=6;
c=1;
d=2;
let a="(b==5)?c:d"
echo $a # 2
记住" expression "等价于$((expression))
如果条件仅仅是检查是否设置了变量,甚至还有更短的形式:
a=${VAR:-20}
如果VAR已设置,则会将VAR值赋给a,否则将为其赋值默认值20——这也可以是表达式的结果。
这种方法在技术上称为“参数展开”。
有些人已经提出了一些不错的替代方案。我想让语法尽可能接近,所以我写了一个名为?的函数。
这允许使用以下语法:
[[ $x -eq 1 ]]; ? ./script1 : ./script2
# or
? '[[ $x -eq 1 ]]' ./script1 : ./script2
在这两种情况下,:都是可选的。所有有空格的参数都必须加引号,因为它使用eval运行它们。
如果<then>或<else>子句不是命令,则函数返回正确的值。
./script; ? Success! : "Failure :("
这个函数
?() {
local lastRet=$?
if [[ $1 == --help || $1 == -? ]]; then
echo $'\e[37;1mUsage:\e[0m
? [<condition>] <then> [:] <else>
If \e[37;1m<then>\e[0m and/or \e[37;1m<else>\e[0m are not valid commands, then their values are
printed to stdOut, otherwise they are executed. If \e[37;1m<condition>\e[0m is not
specified, evaluates the return code ($?) of the previous statement.
\e[37;1mExamples:\e[0m
myVar=$(? "[[ $x -eq 1 ]] foo bar)
\e[32;2m# myVar is set to "foo" if x is 1, else it is set to "bar"\e[0m
? "[[ $x = *foo* ]] "cat hello.txt" : "cat goodbye.txt"
\e[32;2m# runs cat on "hello.txt" if x contains the word "foo", else runs cat on
# "goodbye.txt"\e[0m
? "[[ $x -eq 1 ]] "./script1" "./script2"; ? "Succeeded!" "Failed :("
\e[32;2m# If x = 1, runs script1, else script2. If the run script succeeds, prints
# "Succeeded!", else prints "failed".\e[0m'
return
elif ! [[ $# -eq 2 || $# -eq 3 || $# -eq 4 && $3 == ':' ]]; then
1>&2 echo $'\e[37;1m?\e[0m requires 2 to 4 arguments
\e[37;1mUsage\e[0m: ? [<condition>] <then> [:] <else>
Run \e[37;1m? --help\e[0m for more details'
return 1
fi
local cmd
if [[ $# -eq 2 || $# -eq 3 && $2 == ':' ]]; then
cmd="[[ $lastRet -eq 0 ]]"
else
cmd="$1"
shift
fi
if [[ $2 == ':' ]]; then
eval "set -- '$1' '$3'"
fi
local result=$(eval "$cmd" && echo "$1" || echo "$2")
if command -v ${result[0]} &> /dev/null; then
eval "${result[@]}"
else
echo "${result[@]}"
fi
}
显然,如果您希望脚本更短,您可以删除帮助文本。
编辑:我不知道?在文件名中充当占位符。它不像*那样匹配任意数量的字符,而是只匹配一个字符。因此,如果您的工作目录中有一个只有一个字符的文件,bash将尝试将文件名作为命令运行。我不知道怎么解决这个问题。我认为使用命令?...Args可能会工作,但是,没有骰子。
let命令支持大多数基本操作符:
let a=b==5?c:d;
当然,这只适用于分配变量;不能执行其他命令。
面向字符串的替代方法,使用数组:
spec=(IGNORE REPLACE)
for p in {13..15}; do
echo "$p: ${spec[p==14]}";
done
输出:
13: IGNORE
14: REPLACE
15: IGNORE