exists.hsh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/hsh
  2. # Bourne shell function for finding executable files in the $PATH
  3. # Intended for legacy shells such as hsh or osh
  4. # Copyright 2017 orbea
  5. # All rights reserved.
  6. #
  7. # Redistribution and use of this script, with or without modification, is
  8. # permitted provided that the following conditions are met:
  9. #
  10. # 1. Redistributions of this script must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
  14. # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. # EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  17. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18. # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  19. # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  20. # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  21. # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  22. # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. exists () {
  24. v=1
  25. while [ "$#" -gt 0 ]; do
  26. arg="$1"; shift
  27. case "$arg" in ''|*/) continue ;; esac
  28. x="`printf %s "$arg" | cut -d '/' -f 2-`"
  29. z="`printf %s "$arg" | cut -d '/' -f 1`"
  30. [ ! -f "$z/$x" ] || [ ! -x "$z/$x" ] && [ "$z/$x" = "$arg" ] && continue
  31. [ "$x" = "$z" ] && [ -x "$z/$x" ] && [ ! -f "$arg" ] && z=
  32. p=":$z:$PATH"
  33. while [ "$p" != "`printf %s "$p" | cut -d ':' -f 1`" ]; do
  34. p="`printf %s "$p" | cut -d ':' -f 2-`"
  35. d="`printf %s "$p" | cut -d ':' -f 1`"
  36. [ -f "$d/$x" ] && [ -x "$d/$x" ] && printf %s\\n "$d/$x" && v=0 && break
  37. done
  38. done
  39. return "$v"
  40. }
  41. exists "$@"