#!/bin/bash get_path_fork_level() { # Desc: Get fork level from two paths # Input: arg1 str path # arg2 str path # Output: stdout int fork level # Version: 0.0.1 local path1="$1"; local path2="$2"; # Squeeze multiple slashes and remove trailing slashes path1="$(echo "$path1" | tr -s '/' | sed 's:/*$::' )"; path2="$(echo "$path2" | tr -s '/' | sed 's:/*$::' )"; # Check for mixed absolute/relative paths if [[ "$path1" =~ ^/ ]] && [[ "$path2" =~ ^/ ]]; then flag_root=true; # Remove initial / path1="$(echo "$path1" | sed -e 's:^/::' )"; path2="$(echo "$path2" | sed -e 's:^/::' )"; elif [[ ! "$path1" =~ ^/ ]] && [[ ! "$path2" =~ ^/ ]]; then flag_root=false; else declare -p path1 path2 flag_root; echo "FATAL:Mixed relative and absolute paths not supported." 1>&2; return 1; fi; # Save path as arrays with `/` as element delimiter local IFS='/'; read -ra parts1 <<< "$path1"; read -ra parts2 <<< "$path2"; # Get fork level by counting identical path elements from rootside local fork_level=0; for (( i=0; i<${#parts1[@]} && i<${#parts2[@]}; i++ )); do if [[ "${parts1[i]}" != "${parts2[i]}" ]]; then break; fi; ((fork_level++)); done; echo "$fork_level"; #declare -p path1 path2 flag_root parts1 parts2 fork_level; # debug return 0; }; # Get fork level int from two paths printf "========Test 1========\n"; # fork at 0 p1="foo"; p2="bee"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 2========\n"; # fork at 1 p1="foo"; p2="foo/bar"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 3========\n"; # fork at 1 p1="foo"; p2="foo/bar/"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 4========\n"; # fork at 2 p1="foo/bar/baz"; p2="foo/bar"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 5========\n"; # fork at 2 p1="/foo/bar/baz"; p2="/foo/bar"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 6========\n"; # ERROR: No mixed p1="foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 7========\n"; # fork at 0 p1="/foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 8========\n"; # # ERROR: No mixed p1="/foo/bar/baz"; p2="foo"; declare -p p1 p2; get_path_fork_level "$p1" "$p2"; printf "========Test 9========\n"; # fork at 3 p1="foo///////////bar////////baz//////"; p2="foo/////////bar/////////baz///bee"; declare -p p1 p2; get_path_fork_level "$p1" "$p2";