Last active
December 18, 2015 18:06
-
-
Save Error601/e2a76c47bb02aaa57cb2 to your computer and use it in GitHub Desktop.
Recursively search parent folders for a specific file or folder.
This file contains 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 | |
# The function below will recursively search parent folders | |
# from the current folder (or specified starting folder) | |
# until it finds a matching file or folder, then returns | |
# the full absolute path to that file or folder. | |
# | |
# Run this script where it's stored or call the 'getFilePath' function | |
# if included as a source in another script. | |
# | |
# Usage: | |
# $ ./getFilePath.sh filename.txt /foo/bar/base_folder | |
##=> /foo/filename.txt | |
# | |
# FILE_PATH=$(getFilePath foldername /foo/bar/deeply/nested/folder) | |
##=> /foo/bar/foldername | |
# | |
nameInput=$1 | |
baseInput=$2 | |
# check for file $1 in dir $2 and parent dirs recursively | |
getFilePath() { | |
# NEED A FILE/FOLDER NAME! | |
[[ -z $1 ]] && { echo $(pwd); return 0; } | |
# reset filePath each time | |
filePath="" | |
name=$1 | |
# save Original Working Directory | |
OWD=$(pwd) | |
# set baseDir to the current folder... | |
baseDir=${OWD} | |
# ...unless specified as a second argument | |
[[ ! -z $2 ]] && { baseDir=$2; } | |
# start in baseDir | |
cd ${baseDir} | |
# reset baseDir var to current dir | |
baseDir="." | |
while [[ ${filePath} == "" ]]; do | |
if [[ -e $1 ]]; then | |
filePath=$(pwd)/$1 | |
break | |
else | |
cd ../ | |
fi | |
[[ $(pwd) == "/" ]] && { break; } | |
done | |
if [[ ${filePath} != "" ]]; then | |
echo ${filePath} | |
else | |
echo "not found" | |
fi | |
# take user back to original folder | |
cd ${OWD} | |
} | |
getFilePath ${nameInput} ${baseInput} | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment