嵌套如果bash中的大小写总是评估为true

时间:2017-02-15 16:24:05

标签: bash

if if case应评估为“upload true”if

  • upload已设置
  • os未设为“ios”或version未设为“公开”

我试过了:

#!/bin/bash -e

# should be upload false
upload=true
os="ios"
version="public"

[[ "${os}" == "ios" && "${version}" == "public" ]] && isIosPublicVersion=1

if [[ -n $upload ]] && [[ !$isIosPublicVersion ]]; then
  echo "upload true"
else
  echo "upload false"
fi


# should be upload true
upload=true
os="ios"
version="private"

[[ "${os}" == "ios" && "${version}" == "public" ]] && isIosPublicVersion=1

if [[ -n $upload ]] && [[ !$isIosPublicVersion ]]; then
  echo "upload true"
else
  echo "upload false"
fi

但两者都屈服于“上传真实”

mles-MacBook-Pro:test-ionic mles$ ./test.sh 
upload true
upload true

如何正确设置If案例?

//编辑 [[ $isIosPublicVersion -ne 1 ]][[ ! $isIosPublicVersion ]]评估两个测试始终“上传错误”

2 个答案:

答案 0 :(得分:2)

这应该有效:

if [[ -n "$upload" && "$isIosPublicVersion" != 1 ]]; then
  echo "upload true"
else
  echo "upload false"
fi

或者根据Benjamin W的评论:

if [[ -n $upload ]] && [[ ! $isIosPublicVersion ]]; then

至于代码,使用set -x启用调试模式:你会看到Bash在做什么:

$ ./k.bash
1
+ [[ -n true ]] # [[ -n $upload ]]
+ [[ -n !1 ]]   # [[ !$isIosPublicVersion ]]
+ echo 'upload true'

答案 1 :(得分:2)

问题的根源是

library(shiny)

shinyServer <- function(input, output) {
    filedata <- reactive({
     infile <- input$Samples
     if (is.null(infile)) {
        # User has not uploaded a file yet
        return(NULL)
    }
    read.table(infile$datapath,sep="\t",skip =0, header = TRUE,na.strings = "NA",stringsAsFactors=FALSE)
    })

    observeEvent(input$Click, {
     df <- filedata()
     selectA <- df[complete.cases(df[,3]),]
    }
}

应该是

[[ !$isIosPublicVersion ]]

但是这只是测试“[[ ! $isIosPublicVersion ]] 不是非零/”,即如果它为null则求值为true,否则求值为false。具体来说,如果$isIosPublicVersion具有任何值,例如“0”,它也是错误的。我会使测试更明确,并始终将$isIosPublicVersion设置为某个值:

$isIosPublicVersion

或者(可能最不容易出错),您可以完全抛弃变量并进行更复杂的测试:

if [[ $os == ios && $version == public ]]; then
    isIosPublicVersion=1
else
    isIosPublicVersion=0
fi

if [[ -n $upload && $isIosPublicVersion == 0 ]]; then
  echo "upload true"
else
  echo "upload false"
fi