To count the number of common files, directory files, and other files in a directory, you must first know which files are in this folder. Then, you can determine which files are common files, directory files, or other file types. In fact, you can use the LS command to know which files are in this folder.
Then, it is implemented through the for loop in the shell script. The key is that if you get the names of all the files in the folder, you can use $ (…) at this time (......) . Code:
#! /bin/bashlet "dir_number=0"let "file_number=0"let "other_file=0"for file in $(ls $1)do if [ -d $file] then let "dir_number+=1" elif [ -f $file ] then let "file_number+=1" else then let "other_file+=1" fidoneecho "directoy number is $dir_number"echo "file numberis $file_number"echo "other file number is $other_number"
The above is the code implementation for statistics of various files through the for loop. If you want to use the while loop, how should you write the code? In fact, the key part is the same as the for loop. The difference is how to determine the exit of the program. The program code is:
#! /bin/bashlet "dir_number=0"let "file_number=0"let "other_file=0"set $(ls $1)while [ "$1" != "" ]do if [ -d $1] then let "dir_number+=1" elif [ -f $1 ] then let "file_number+=1" else then let "other_file+=1" fi shiftdoneecho "directoy number is $dir_number"echo "file numberis $file_number"echo "other file number is $other_number"
The key is to use the set command and $ (......) The LS command result is the file. As a different domain, and then use the $1 command together with the shift command to determine all files in the directory, so as to count all types of formats in all files.
In addition to the preceding methods, you can also use the colon command in the while loop. The colon command can simplify the logic, which is equivalent to an alias of true. In addition, because the colon command is a built-in command, it runs faster than true. The specific implementation code is:
#! /bin/bashlet "dir_number=0"let "file_number=0"let "other_file=0"set $(ls $1)while :do if [ "$1" == "" ] then break fi if [ -d $1] then let "dir_number+=1" elif [ -f $1 ] then let "file_number+=1" else then let "other_file+=1" fi shiftdoneecho "directoy number is $dir_number"echo "file numberis $file_number"echo "other file number is $other_number"
The above is the specific implementation code for counting the number of various files in the directory.