有这样的方法吗

int a = (b == 5) ? c : d;

使用Bash ?


当前回答

这是通解

也适用于字符串测试 感觉更像是一种表达 避免在条件失效时产生任何微妙的副作用

数值比较试验

a=$(if [ "$b" -eq 5 ]; then echo "$c"; else echo "$d"; fi)

字符串比较测试

a=$(if [ "$b" = "5" ]; then echo "$c"; else echo "$d"; fi)

其他回答

简单的三元

brew list | grep -q bat && echo 'yes' || echo 'no'

此示例将确定您是否使用自制程序安装bat

如果是,你会看到"是"

如果是false,你会看到"no"

我在这里添加了-q来抑制grepped字符串输出,所以你只能看到“yes”或“no”

真正的模式是这样的

doSomethingAndCheckTruth && echo 'yes' || echo 'no'

用bash和zsh测试

三元运算符?:是if/else的缩写形式

case "$b" in
 5) a=$c ;;
 *) a=$d ;;
esac

Or

 [[ $b = 5 ]] && a="$c" || a="$d"

有些人已经提出了一些不错的替代方案。我想让语法尽可能接近,所以我写了一个名为?的函数。

这允许使用以下语法:

[[ $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可能会工作,但是,没有骰子。

回答: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))

[ $b == 5 ] && { a=$c; true; } || a=$d

这将避免在&&和||之间的代码失败时意外执行||之后的部分。