shell 學習之case語句

2021-09-21 23:12:37 字數 3415 閱讀 1974

一般建議變數用引號括起來

-v 顯示資訊 

case 

shift

把剛才的變數踢掉

一、case語句:語法結構

case stitch in

value1)

statement

...;;

value2)

statement

...;;

*);;

esac

示例(給出選項讓使用者選擇,然後根據使用者所選顯示出相應的資訊):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

[root@lovelacecase]# cat showmenu.sh

#!/bin/bash

#version:0.1

#auther:lovelace

#pragram:show menu and wait user choice

#

#difine an function to display the menu

showmenu()

#call showmenu function

echo

showmenu

echo

#read the argument for user input

read-p"your choice is:"choice

#use while statement to loop

while["$choice"!="q"-o"$choice"!="q"];do

#jugement the choice values and dispaly the result

case$choicein

d|d)

echo"disk information:"

df-h

;;

m|m)

echo"memory information:"

free-m |grep"mem"

;;

s|s)

echo"swap information:"

free-m |grep"swap"

;;

q|q)

echo"quitting...."

exit8

;;

*)

echo"unknow argument."

;;

esac

#call showmenu function again

echo

showmenu

#read user input again

echo

read-p"please select again:"choice

done

後記:這個好像就只是提了下case的語法結構,case在進行條件判斷的時候相對於if來講,個人更直觀一些,不管怎麼講,指令碼注重的是實現的目的,而不是過程,所以不管黑貓白貓,只要能抓住老鼠,就是好貓。

SHELL學習之 case語句

case語句是點名語句,每個分支語句之間是平衡的,在進行判定時,每個分支語句之判定一次,適合於字元匹配。if else 語句適合在判斷時用,if語句每個分支語句之間是有優先順序的,在進行判定時,每個語句都要判定一次。case語句和if語句相比,判定次數少。root fuwu test cat cas...

shell邏輯控制語句之case

case分支判斷結構 語法 case 變數名稱 in value1 statement statement value2 statement statement value3 statement statement statement statement esac 編寫指令碼,判斷使用者輸入的字串 ...

shell程式設計 case語句

case語句格式 vi test.sh echo input read num echo the input data is num case num in 1 echo january 雙分號結束 2 echo feburary 5 echo may 每個case可以有多條命令 echo sdfd...