From 3ec74d1c8d0804df823fbba03b6cd53b9ecad1e4 Mon Sep 17 00:00:00 2001 From: Bas Huis Date: Mon, 13 Aug 2018 02:04:30 +0200 Subject: [PATCH] Find dir where certain dir or file exists --- README.md | 24 ++++++++++++++++++++++++ test.sh | 11 ++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6aa046e..40fa1a6 100644 --- a/README.md +++ b/README.md @@ -1013,6 +1013,30 @@ $ basename ~/Pictures/Downloads/ Downloads ``` +## Find parent directory that contains a certain file or directory + +**Example Function:** + +```sh +parent_find() { + [[ $1 == '/' ]] && return 1 + + [[ -e "$1/$2" ]] && printf '%s\n' "$1" && return 0 + + parent_find "$(dirname "$(realpath "$1")")" "$2" +} +``` + +**Example Usage:** + +```shell +$ pwd +/home/black/Projects/awesome/src/assets + +$ parent_find "$PWD" .git +/home/black/Projects/awesome/ +``` + diff --git a/test.sh b/test.sh index 01020f3..4d5a815 100755 --- a/test.sh +++ b/test.sh @@ -1,5 +1,4 @@ #!/usr/bin/env bash -# shellcheck source=/dev/null # # Tests for the Pure Bash Bible. @@ -109,6 +108,16 @@ test_basename() { assert_equals "$result" "1.jpg" } +test_parent_find() { + local dir="$PWD/" + + cd ./manuscript/ + + assert_equals "$dir" "$(parent_find "$PWD" .git)" + + cd ../ +} + test_hex_to_rgb() { result="$(hex_to_rgb "#FFFFFF")" assert_equals "$result" "255 255 255"