How to write an if-statement within a if-statement
How can I write something like:
if $1 = 开发者_运维问答a then
check second statementif $2 is b then echo a and b
else $1 = 1 then
check second statementif $2 = 2 then echo 1 and 2
...where all of the variables are strings?
This is what I have:
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
}
Using a nested case statement could help you: Nested case in bash script
Your function would look like this:
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
}
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
}
"then" should be after each "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
}
精彩评论