chemoelectric

cleanpath in zsh

Oct 24th, 2025
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #!/usr/bin/env nix-shell
  2. #! nix-shell -i zsh -p zsh --pure
  3.  
  4. #
  5. # Remove empty and duplicate entries from a colon-separated path.
  6. #
  7. # For example: ":a:b:b:::c:a::" --> "a:b:c"
  8. #
  9.  
  10. # Ensure that the script uses only built-in shell commands.
  11. PATH=''
  12.  
  13. delete_duplicates() {
  14. if [[ ${#entries} -ne 0 ]]; then
  15. local i=1
  16. while [[ ${i} -lt ${#entries} ]]; do
  17. local j=
  18. (( j=${i} + 1 ))
  19. while [[ ${j} -le ${#entries} ]]; do
  20. if [[ "${entries[${i}]}" == "${entries[${j}]}" ]]; then
  21. # Delete the duplicate entry.
  22. entries[${j}]=()
  23. else
  24. (( j=${j} + 1 ))
  25. fi
  26. done
  27. (( i=${i} + 1 ))
  28. done
  29. fi
  30. }
  31.  
  32. if [[ ${#} != 1 ]]; then
  33. echo "${0}: command line error" 1>&2
  34. echo "Usage: ${0} PATH" 1>&2
  35. exit_status=1
  36. else
  37. dirty_path="${1}"
  38.  
  39. # Split the path at ':' characters.
  40. entries=(${(s/:/)dirty_path})
  41.  
  42. delete_duplicates
  43.  
  44. # Join the path with ':' characters.
  45. clean_path="${(j/:/)entries}"
  46.  
  47. echo -n "${clean_path}"
  48.  
  49. exit_status=0
  50. fi
  51.  
  52. exit ${exit_status}
  53.  
Advertisement
Add Comment
Please, Sign In to add comment