Switch is used to jump and run a certain case as per the result of the condition or expression is evaluated. It acts as an alternative to using multiple if in bash and keeps bash script much clear and readable.
The syntax of switch
is as follows:
case $variable in pattern1) # Tasks to be executed ;; pattern2) # Tasks to be executed ;; … pattern n) # Tasks to be executed ;; *) esac
In syntax, $variable
is the expression or value that needs to be matched among the list of choices provided.
In each choice, a pattern or a combination of patterns can be specified. The ;;
tells bash that end of given choice block. The esac
keyword specify end of case block.
The following is an example to count the number of files and directories in a given path:
#!/bin/bash # Filename: switch_case.sh # Description: Using case to find count of directories and files in a # path echo "Enter target path" read path files_count=0 dirs_count=0 for file in 'ls -l $path | cut -d ' ' -f1' do case "$file" in d*) dirs_count='expr $dirs_count + 1 ' ;; -*) files_count='expr $files_count + 1' ;; *) esac done echo "Directories count = $dirs_count" echo "Regular file count = $files_count"
The output after running this script is as follows:
Enter target path /usr/lib64 Directories count = 134 Regular file count = 1563
In this example, we first read an input path from a user using the read
shell builtin. Then, we initialize the counter variable of files and directories count to 0
. Furthermore, we use ls -l $path | cut -d ' ' -f1
to get a long list of file attributes of the path content and then retrieve its first column. We know that the first character of the first column of ls -l
tells the type of the file. If it is d
, then it is a directory, and -
represents a regular file. The dirs_count
or files_count
variables get incremented accordingly.
3.12.74.189