如何在if语句中编写if语句

时间:2011-06-07 09:39:00

标签: bash

我怎么写像:

  • if $1 = a then检查第二个语句if $2 is b then echo a and b
  • else $1 = 1 then检查第二个语句if $2 = 2 then echo 1 and 2

...所有变量都是字符串?

这就是我所拥有的:

fun() {
  if [ "$1" == "a" ]; # when $1 is a then
  then
    if [ "$2" == "" ]; # $1 is a and $2 is empty string
      echo a
    elif [ "$2" == "b" ]; # $1 is a and $2 is b
    then
      echo "a and b"
     fi
   fi
  else
    if [ "$1" == "1" ]; # when $1 is 1 then
    then
      if [ "$2" == "" ]; # $1 is 1 and $2 is empty string
        echo a
       elif [ "$2" == "2" ]; #$1 is 1 and $2 is 2
       then
         echo "1 and 2"
       fi
    fi
}

3 个答案:

答案 0 :(得分:3)

使用嵌套的case语句可以帮助您:Nested case in bash script

你的功能如下:

fun(){
  case "$1" in
    "a")                      # $1 is 'a'
      case "$2" in
        "")  echo "$1";;      # only $1 present
        "b") echo "a and b";; # $1 is 'a' and $2 is 'b'
      esac;;
    "1")                      # $1 is '1'
      case "$2" in
        "")  echo "$1";;      # only $1 present
        "2") echo "1 and 2";; # $1 is '1' and $2 is '2'
      esac;;
  esac
}

答案 1 :(得分:1)

fun() {   
  if [ "$1" == "a" ]; # when $1 is a then
  then
    if [ "$2" == "" ]; # $1 is a and $2 is empty string
    then # was missing
      echo a
    elif [ "$2" == "b" ]; # $1 is a and $2 is b
    then
      echo "a and b"
    fi
  # fi # shouldn't be here if you want to have else
  else
    if [ "$1" == "1" ]; # when $1 is 1 then
    then
      if [ "$2" == "" ]; # $1 is 1 and $2 is empty string
      then
        echo a
      elif [ "$2" == "2" ]; #$1 is 1 and $2 is 2
      then
        echo "1 and 2"
      fi
    fi
  fi
}

答案 2 :(得分:0)

“那么”应该在每个“如果”之后 fun() { if [ "$1" == "a" ]; # when $1 is a then then if [ "$2" == "" ]; # $1 is a and $2 is empty string then #### 1st omitted "then" echo a elif [ "$2" == "b" ]; # $1 is a and $2 is b then echo "a and b" fi # fi #### this fi should be in the end else if [ "$1" == "1" ]; # when $1 is 1 then then if [ "$2" == "" ]; # $1 is 1 and $2 is empty string then #### 2nd omitted "then" echo a elif [ "$2" == "2" ]; #$1 is 1 and $2 is 2 then echo "1 and 2" fi fi fi #### here }