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
- dotglob
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.
Here is sample shell script to see if *.mp3 exists or not in a directory:
- listFE.sh
One usage example:
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:
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
- dotglob
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.
Here is sample shell script to see if *.mp3 exists or not in a directory:
- listFE.sh
- #!/bin/sh
- old=$(pwd)
- [ $# -lt 2 ] && echo -e "\t[Info] Give arg1=Folder path; arg2=File extension!\n" && exit 1
- [ -d $1 ] && cd $1 || exit 2
- shopt -s nullglob
- found=0
- for i in *.$2; do
- echo "File $i found" # or take other action
- found=1
- done
- shopt -u nullglob
- [ $found -eq 0 ] && echo "Directory is empty"
- cd $old
Without nullglob i will expand to *.
沒有留言:
張貼留言