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.
a] 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.
b] 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 # enableHere is sample shell script to see if *.mp3 exists or not in a directory:
shopt -u nullglob # disable
#!/bin/bashWithout nullglob i will expand to *.mp3 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:
old=$(cd)
[ $# -eq 0 ] && exit 1
[ -d $1 ] && cd $1 || exit 2
shopt -s nullglob
found=0
for i in *.mp3; do
echo "File $i found" # or take other action
found=1
done
shopt -u nullglob
[ $found -eq 0 ] && echo "Directory is empty"
cd $old
find ~/project/editor -maxdepth 0 -empty -exec echo {} directory is empty. \;Where,
- -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.
No comments:
Post a Comment