Now I want to execute 1 and 2 if 1 is matched and only 2 if 2 is matched..
Like the example bellow in C switch case.
switch case traverses all the case statements if break is not specified. if 1 matches it prints 12 if 2 is matched then it prints only 2
case 1) printf("1") ;
case 2) printf("2") ;
break;
复制代码
You can try:
case $pattern in
1)
echo -n "1"
;;
1|2)
echo -n "2"
;;
esac
复制代码
or:
if [[ "$pattern" == "2" ]]; then
if [[ "$pattern" == "1" ]]; then
echo -n "1"
fi
echo -n "2"
fi
复制代码
Some special one might be like:
#!/bin/bash
pattern=1
limit=4
while [ $pattern -le $limit ]
do
printf "$pattern"
pattern=$((pattern + 1))
done
echo
复制代码
or the same result can be achieved in recent bash with a single piped statement, as:
echo {1..4} | sed 's/ //g'
复制代码
A more flexible example like:
case $pattern in
1) echo " statements for pattern 1 match will be executed \n "
;;
2) echo " statements for patter 2 match will be executed \n"
;;
3) echo " statement for patter 3 match will be executed "
;;
esac;
复制代码
now how do I make this script print
Statement for pattern 1 match will be executed
Statement for pattern 2 match will be executed
when the patther=1
i.e when I give patter=1 then two cases should be executed 1 and 2 Like in C language switch() case statements.
You dont give a break; statements the statements gets executed for the perticular case untill a break is found.
if I give in C:
switch(var1)
{
case 1: printf(" Statement for pattern 1 match will be executed") ;
case 2: printf ("Statement for pattern 2 match will be executed ") ;
break;
case 3: printf ("Statement for pattern 3 match will be executed ") ;
break ;
}
复制代码
I achive what I want from the above C snippet. I want to achive the same in shell script.
you can mimic the behaviour of C/C++ (which depends on the presence or absence of the break statement) in this way:
#!/bin/bash
pattern=1
while [ $pattern != BREAK ]
do
case $pattern in
1)
echo 1
pattern=2
;;
2)
echo 2
pattern=3
;;
3)
echo 3
pattern=BREAK
;;
4)
echo 4
pattern=5
;;
5)
echo 5
pattern=BREAK
;;
*)
pattern=BREAK
;;
esac
done
复制代码
The case statement is inside a while loop which will be executed until the pattern is equal to a keyword (BREAK). At each matching condition the pattern is updated to the next one. In this way the test is repeated and the result is exactly what you're trying to get. Note that you can insert BREAK at any point in the case construct.
AND: In place of ;; we can use ;& (unconditional follow up) and ;;& (conditional follow up). So, the following will print 12, if the pattern is 1 and will print 2, if the pattern is 2.
case $pattern in
1)
echo "1"
;&
2)
echo "2"
;;
esac
复制代码
Another point to note. I think it is a new feature in the newer versions of bash. I'm sure this would not have been existing back in 2008. Though I dont have when this feature got into bash but I can say that bash-3.0 dint have it.