有这样的方法吗

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

使用Bash ?


当前回答

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

这允许使用以下语法:

[[ $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;

当然,这只适用于分配变量;不能执行其他命令。

这里有另一个选项,你只需要指定你分配一次的变量,不管你分配的是字符串还是数字:

VARIABLE=`[ test ] && echo VALUE_A || echo VALUE_B`

只是一个想法。:)

在Shell Scripting中,我们可以使用以下三种方式用于三元运算符:

    [ $numVar == numVal ] && resVar="Yop" || resVar="Nop"

Or

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

Or

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

更新:使用以下准备运行的示例扩展字符串计算的答案。这是利用上面提到的第二种格式。

$ strVar='abc';resVar=$([[ $strVar == 'abc' ]] && echo "Yop" || echo "Nop");echo $resVar
Yop
$ strVar='aaa';resVar=$([[ $strVar == 'abc' ]] && echo "Yop" || echo "Nop");echo $resVar
Nop

面向字符串的替代方法,使用数组:

spec=(IGNORE REPLACE)
for p in {13..15}; do
  echo "$p: ${spec[p==14]}";
done

输出:

13: IGNORE
14: REPLACE
15: IGNORE
[ $b == 5 ] && { a=$c; true; } || a=$d

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