linux shell—–case statement

來源:互聯網
上載者:User
The case StatementThe case statement is good alternative to Multilevel if-then-else-fi statement. It enable you to match several
values against one variable. Its easier to read and write.Syntax:

           case  $variable-name  in                pattern1)   command                                ...                                ..                                command;;                pattern2)   command                                ...                                ..                                command;;                patternN)   command                                ...                                ..                                command;;                *)             command                                ...                                ..                                command;;           esac

The $variable-name is
compared against the patterns until a match is found. The shell then executes all the statements up to the two semicolons that are next to each other. The default is *) and its executed if no match is found. For e.g. write script as follows:
#
if no vehicle name is given
# i.e. -z $1 is defined and it is NULL
#
# if no command line arg

if [ -z $1 ]
then
  rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as rental
  rental=$1
fi

case $rental in
   "car") echo "For $rental Rs.20 per k/m";;
   "van") echo "For $rental Rs.10 per k/m";;
   "jeep") echo "For $rental Rs.5 per k/m";;
   "bicycle") echo "For $rental 20 paisa per k/m";;
   *) echo "Sorry, I can not gat a $rental for you";;
esac

First script will check, that if $1(first command line argument) is given or not, if NOT given set value of rental
variable to "*** Unknown vehicle ***",if command line arg is supplied/given set value of rental variable to given value (command line arg). The $rental is compared against the patterns until a match is found.
For first test run its match with van and it will show output "For
van Rs.10 per k/m."
For second test run it print, "For
car Rs.20 per k/m".
And for last run, there is no match for Maruti-800, hence default i.e. *) is executed and it prints, "Sorry,
I can not gat a Maruti-800 for you".
Note that
esac is always required to indicate end of case statement.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.