Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

4.3.4 case conditional test statement


May 23, 2021 That's what Linux should learn



If you've studied C language before, seeing the title of this section will certainly make you smile, "This is not a switch statement!" " Yes, case conditional test statements are very similar to switch statements! T he case statement matches the data in multiple ranges, executes the relevant command and ends the entire conditional test if the match is successful, and executes the default command defined in the asterisk if the data is not in the range listed. The syntax structure of the case statement is shown in Figure 4-22.

4.3.4 case conditional test statement

Figure 4-22 case condition tests the syntax structure of the statement

In the previously described Guess.sh a fatal weakness in the script - only numbers can be accepted! Y ou can try entering a letter and you'll notice that the script crashes immediately. T he reason is that letters cannot be sized with numbers, for example, the proposition "a is greater than or equal to 3" is completely wrong. We must have some measures to judge the user's input, when the user input is not a number, the script can be prompted, thus avoiding crash.

By combining case conditional test statements and wildcards in your script (see Chapter 3), you can fully meet the requirements here. Next, we write Checkkeys.sh script, prompt the user to enter a character and assign it to the variable KEY, and then show the user whether its value is a letter, number, or other character based on the value of the variable KEY.

[root@linuxprobe ~]# vim Checkkeys.sh

!/bin/bash

  1. read -p "请输入一个字符,并按Enter键确认:" KEY
  2. case "$KEY" in
  3. [a-z]|[A-Z])
  4. echo "您输入的是 字母。"
  5. ;;
  6. [0-9])
  7. echo "您输入的是 数字。"
  8. ;;
  9. *)
  10. echo "您输入的是 空格、功能键或其他控制字符。"
  11. esac
  12. [root@linuxprobe ~]# bash Checkkeys.sh
  13. 请输入一个字符,并按Enter键确认:6
  14. 您输入的是 数字。
  15. [root@linuxprobe ~]# bash Checkkeys.sh
  16. 请输入一个字符,并按Enter键确认:p
  17. 您输入的是 字母。
  18. [root@linuxprobe ~]# bash Checkkeys.sh
  19. 请输入一个字符,并按Enter键确认:^[[15~
  20. 您输入的是 空格、功能键或其他控制字符。