【问题标题】:Bash If Else statement inside one line command一行命令中的 Bash If Else 语句
【发布时间】:2020-04-23 12:55:44
【问题描述】:

我有一个案例:

case $1 in
  "start") exec docker-compose up ;;
  "check-types") docker-compose run --rm myapp mypy --config-file=mypy.ini $2;;
  "help" | *) print-help ;;
esac

我想用 if 声明替换写在 "check-types" 中的 $2 声明类似于:

if [[ $2 ]]; then
  $2
else
  .
fi

这可能在一行 bash 中吗?

所需行为的示例:

  • 写入./cli check-types 执行docker-compose run --rm myapp mypy --config-file=mypy.ini .
  • 写入./cli check-types app/test 执行docker-compose run --rm myapp mypy --config-file=mypy.ini app/test

【问题讨论】:

    标签: bash if-statement case


    【解决方案1】:

    如果$2 为空或未设置,您可以使用:- 运算符指定默认值。

    case $1 in
      "start") 
        exec docker-compose up ;;
      "check-types")
        docker-compose run --rm myapp mypy --config-file=mypy.ini "${2:-.}";;
      "help" | *)
        print-help ;;
    esac

    (不过,一般来说,bash 没有条件表达式。)

    【讨论】:

      猜你喜欢
      • 2013-06-16
      • 2015-05-16
      • 2021-04-24
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多