Created
December 19, 2013 10:03
-
-
Save Erni/8036994 to your computer and use it in GitHub Desktop.
Bash script that mimics the find command taking a directory and filename as arguments. It searches for that filename within that directory and its subdirectories (using BFS algorithm). Usage: search.sh DIR FILENAME
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# initialization of dirstack with the first argument (directory) | |
dirstack=$1 | |
nametofind=$2 | |
# First set bash option to avoid | |
# unmatched patterns expand as result values | |
#shopt -s nullglob | |
# store matching file names into array | |
while [ ${#dirstack[@]} -gt 0 ]; do | |
# read the directory placed in the first element of the stack, and load the files in an array | |
filearray=( "${dirstack[0]}"/* ) | |
filearray=( "${filearray[@]##*/}" ) | |
# check every file if matches the name and whether it is a directory | |
for file in ${filearray[@]}; do | |
dir=${dirstack[0]} | |
if [ $file == $nametofind ]; then | |
echo "Found $dir/$nametofind" | |
fi | |
if [ -d $dir/$file ]; then | |
dirstack[${#dirstack[@]}]=$dir/$file | |
fi | |
done | |
# remove first element of the stack | |
dirstack=(${dirstack[@]:1}) | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment