2011-06-07 143 views
1

我怎么能写这样的:如何中编写一个if语句if语句

  • 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 
} 
+0

'之开关应该效果更好 – ajreal 2011-06-07 09:42:56

+1

使用嵌套的'case'声明可以帮助你:http://stackoverflow.com/questions/1477518/nested-case-in-bash-script – eckes 2011-06-07 09:45:53

+1

和问题在哪里? – Rajish 2011-06-07 09:47:14

回答

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 
} 
+0

完美!谢谢eckes!你又做到了! – devric 2011-06-07 10:30:06

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 
} 
+0

+1眼睛好:) – Rajish 2011-06-07 09:55:47

+0

谢谢leledumbo,但它仍然不起作用 – devric 2011-06-07 10:02:02

0

“,那么“应该在每个”if“之后

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 }