da_Aresinger

dirname reimplementation builtin only

Oct 28th, 2026 (edited)
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.15 KB | Source Code | 0 0
  1. #!/bin/bash
  2.  
  3. no_extglob () {
  4.     local path="${1:-dummy}"    # store argument with dummy fallback
  5.     [[ "$path" =~ ^(.*[^/])/*$ ]]
  6.     path="${BASH_REMATCH[1]:-/}"    # strip trailing /
  7.     [[ "/$path" =~ ^(.+)(/[^/]*/*)$ ]]
  8.     path="${BASH_REMATCH[1]:-.}"    # stript last component and default to curdir
  9.     [[ "$path" =~ ^(.*[^/])/*$ ]]
  10.     path="${BASH_REMATCH[1]:-/}"    # strip trailing /
  11.     echo "${path/#\/?*/${path:1}}"  # strip leading / if strlen>1 (looks weird in vim, but is correct)
  12. }
  13.  
  14. with_extglob () {
  15.     local path="${1:-dummy}"    # store argument with dummy fallback
  16.     path="${path//+(\/)/\/}"    # remove excessive /
  17.     path="/${path%/}"       # strip trailing / and prepare edgecase on next step: 'no / in path'
  18.     path="${path%/?*}"      # strip last component
  19.     path="${path:-.}"       # if empty default to curdir
  20.     echo "${path/#\/?*/${path:1}}"  # strip leading / if strlen>1 (looks weird in vim, but is correct)
  21. }
  22.  
  23. shopt -u extglob
  24. shopt -s extglob # comment out to run without extglob
  25.  
  26. case "$(shopt extglob)" in
  27.     *on)
  28.         #echo "using extglob"
  29.         strategy=with_extglob
  30.         ;;
  31.     *)
  32.         #echo "using regex"
  33.         strategy=no_extglob
  34.         ;;
  35. esac
  36.  
  37. for arg in "$@"; do
  38.     $strategy "$arg"
  39. done
Advertisement
Add Comment
Please, Sign In to add comment