2016年1月28日 星期四

[Linux 文章收集] Use BASH nullglob To Verify *.c Files Exists or Not In a Directory

Source From Here
Introduction
Can you explain me usage of nullglob variable under BASH? How do I check for any *.c files in any directory?

BASH shell has the following two special variables to control pathname expansion. Bash scans each word for the characters *?, and [. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of file names matching the pattern.

nullglob
If set, bash allows patterns which match no files to expand to a null string, rather than themselves. This is useful to check for any *.mp3 or *.cpp files in directory.

dotglob
If set, bash includes filenames beginning with a . in the results of pathname expansion.


How do I set and unset nullglob variable?
Use shopt command to toggle the values of variables. The -s option enable nullglob effects and the -u option disable nullglob option.
# shopt -s nullglob // enable 
# shopt -u nullglob // disable

Here is sample shell script to see if *.mp3 exists or not in a directory:
- listFE.sh
  1. #!/bin/sh  
  2. old=$(pwd)  
  3. [ $# -lt 2 ] && echo -e "\t[Info] Give arg1=Folder path; arg2=File extension!\n" && exit 1  
  4. [ -d $1 ] && cd $1 || exit 2  
  5.   
  6. shopt -s nullglob  
  7. found=0  
  8. for i in *.$2do  
  9.     echo "File $i found" # or take other action  
  10.     found=1  
  11. done  
  12. shopt -u nullglob  
  13. [ $found -eq 0 ] && echo "Directory is empty"  
  14. cd $old  
One usage example:
// List all file with extension .mp3 under folder 'empty'
# ./listFE.sh empty mp3
File test.mp3 found

Without nullglob i will expand to *. only if there are no files in given directory. You can also use GNU find command to find out if directory is empty or not i.e. check for any *.c files in a directory called ~/project/editor:
// -maxdepth 0: Do not scan for sub directories.
// -empty : File is empty and is either a regular file or a directory.
// -exec echo {} directory is empty. \; : Display message if directory is empty.

# find ~/project/editor -maxdepth 0 -empty -exec echo {} directory is empty. \;


沒有留言:

張貼留言

[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...