2011-06-07 183 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 }