The following article describes the basic syntax and includes a simple example of the BASHCASEstatement usage. TheCASEstatement is the simplest form of theIF-THEN-ELSEstatement in BASH. You may use theCASEstatement if you need theIF-THEN-ELSEstatement with manyELIFelements. With the BASHCASEstat...
Also, refer to our earlier article on Bash~ expansaionand{ } expansion. Bash Case Example 3. Find File type from the Extension This example prints type of a file (text, Csource, etc) based on the extension of the filename. $ cat filetype.sh #!/bin/bash for filename in $(ls) do ...
In a Bashcasestatement, the variable holds a value that is used to compare against defined patterns. When thecasestatement is executed, the script compares the input$variableagainst each pattern in the defined order until it finds a match. Once a match is found, the corresponding command associ...
#!/bin/bash filename="example.txt" case "$filename" in *.txt) echo "这是一个文本文件" ;; *.jpg|*.png) echo "这是一个图像文件" ;; *) echo "这是一个未知类型文件" ;; esac ``` 在这个例子中,我们检查了变量filename的文件扩展名。如果文件扩展名为.txt,则输出“这是一个文本文件”...
Amit has a master's degree in computer applications and over 11 years of industry experience in the IT software domain. Cite this lesson This lesson will discuss the use of case statements in Bash. You will learn the structure of case statements and when they are used best. An example wi...
Example 5 – Case statement with return codes Reference scripts Conclusion Case statement syntax The syntax of case statement in bash is given below: case expression in pattern1) STATEMENTS ;; pattern2) STATEMENTS ;; Pattern3 | Pattern4 | pattern5) STATEMENTS ;; ...
status)echo"$name is runing...";;*)echo"Wrong using! input example : start network";;esacelse#如果$name文件不存在echo"$name不存在";case$flaginstart)touch$dir$name;echo"$name服务已创建成功";; stop)echo"停止失败,${name}服务已被其他用户或程序停止";; ...
If we run: ./case_match.sh b## print "b match"./case_match.sh anything## print "none of the case match"echo$?## 1 Example case"$1"in*.tar|*.tgz)tar-xzvf"$1";;*.gz)gunzip-k"$1";;*.zip)unzip-v"$1";;*)echo"Cannot extract$1"exit1;;esac### ./case_match.sh image...
case$variablein pattern1|pattern2) commands ;; pattern3|pattern4) commands ;; Now, let’s take a look at a couple of examples to understand this syntax better. Holidays in a Month For our first example, let’s write a script that takes a month as input from the user and responds wit...
8. 9. If we run: ./case_match.sh b ## print "b match" ./case_match.sh anything ## print "none of the case match" echo $? ## 1 1. 2. 3. 4. 5. 6. Example case "$1" in *.tar|*.tgz) tar -xzvf "$1";;