Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在if语句中编写if语句_Bash - Fatal编程技术网

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

Bash 如何在if语句中编写if语句,bash,Bash,我怎样才能写出这样的东西: 如果$1=a,则检查第二条语句如果$2是b,则回显a和b 否则$1=1,然后检查第二个语句如果$2=2,则回显1和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=a,则检查第二条语句
    如果$2是b,则回显a和b
  • 否则$1=1,然后检查第二个语句
    如果$2=2,则回显1和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
}

使用嵌套的case语句可以帮助您:

您的函数如下所示:

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
}

使用嵌套的case语句可以帮助您:

您的函数如下所示:

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
}
“then”应该在每个“if”之后
fun(){
如果[“$1”==“a”]#当$1是a时,则
然后
如果[“$2”==”]#$1是一个字符串,而$2是空字符串
然后,第一次省略“then”
呼应
elif[“$2”==“b”];#$1是a,$2是b
然后
回音“a和b”
fi
#最后这场比赛应该结束了
其他的
如果[“$1”==“1”]#当$1为1时,则
然后
如果[“$2”==”]#$1是1,而$2是空字符串
然后第二个省略了“then”
呼应
elif[“$2”==“2”];#$1是1,$2是2
然后
回声“1和2”
fi
fi
这里
}

“then”应该在每个“if”之后

fun(){
如果[“$1”==“a”]#当$1是a时,则
然后
如果[“$2”==”]#$1是一个字符串,而$2是空字符串
然后,第一次省略“then”
呼应
elif[“$2”==“b”];#$1是a,$2是b
然后
回音“a和b”
fi
#最后这场比赛应该结束了
其他的
如果[“$1”==“1”]#当$1为1时,则
然后
如果[“$2”==”]#$1是1,而$2是空字符串
然后第二个省略了“then”
呼应
elif[“$2”==“2”];#$1是1,$2是2
然后
回声“1和2”
fi
fi
这里

}

使用嵌套的
case
语句可以帮助您:在这种情况下如何编写开关?我是一名编码初学者,在Bash中称为
case
switch
,在类似C的语言中)。遵循@eckes'链接(该评论应该是(被接受的)答案)IMHO。使用嵌套的
case
语句可以帮助您:在这种情况下我将如何编写开关?我是一名编码初学者,在Bash中称为
case
switch
,在类似C的语言中)。遵循@eckes'链接(该评论应为(接受的)答案)IMHO。