2017年4月28日 星期五

[Linux 常見問題] Check whether a certain file type/extension exists in directory

Source From Here 
Question 
How would you go about telling whether files of a specific extension are present in a directory, with bash? 

How-To 
Consider below shell script: 
- test.sh 
  1. #!/bin/sh  
  2. EXT=$1  
  3. count=`ls -1 test/*.$EXT 2>/dev/null | wc -l`  
  4. if [ $count -ge 1 ]; then  
  5.     echo "Folder test contains file with extension '$EXT'"  
  6. else  
  7.     echo "Folder test contains no file with extension '$EXT'"  
  8. fi  
Then you can use it this way: 
# ls test/ // Check the files under folder test
abc.txt def.txt output.log test.log
# ./test.sh log // Check if the folder test contains file with extension as 'log'
Folder test contains file with extension 'log'
# ./test.sh txt // Check if the folder test contains file with extension as 'txt'
Folder test contains file with extension 'txt'
# ./test.sh exe // Check if the folder test contains file with extension as 'exe'
Folder test contains no file with extension 'exe'

Below is the extended usage to show file with desired extension: 
- test2.sh 
  1. #!/bin/sh  
  2. EXT=$1  
  3. ARRAY=($(ls -1 test/*.$EXT))  
  4. echo "List file with extension($EXT):"  
  5. for f in "${ARRAY[@]}"  
  6. do  
  7.     echo -e "\t$f"  
  8. done  
Supplement 
How do I assign ls to an array in Linux Bash? 
nixCraft - Bash Iterate Array Examples 

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...